Parsing a 'template' in rails (alternatives to gsub) - ruby-on-rails

I have a 'template' system in my CMS rails app. Basically the whole HTML template is stored in a database column and it has key code in the string (like <!--THEME_Body-->) that gets replaced with content generated by the application.
I use an actual layout to render the template. All that is in the layout is:
<%= generate_theme.gsub!('<!--THEME_Body-->', yield) -%>
That helper takes the correct theme and further gsubs other area like Meta data and Breadcrumbs.
I'm just wondering if there's a better way to go about this? Perhaps using content_for or something like that?

That's a pretty good way of going about it, although I would make use of Ruby's sexy syntax to combine all the lines into something a little more syntactically correct - it speeds the script up and it looks a damn sight nicer too!
tags = {
'<!--THEME_Body-->' => yield,
'<!--THEME_Head-->' => yield(:head),
'<!--STYLESHEET-->' => stylesheet_link_tag('application')
}
tags.each { |str, rep| generate_theme.gsub!(str, rep) }
Bear in mind that this code should not go in a view - it should ideally be put in a model, as it's to do with the application's data, but it could also go in a helper somewhere. If it's an instance variable in a model, you could just call
generate_theme.parse
And that code could be executed - it looks a lot better and sticks to the standard MVC convention of cleaning up the view as much as possible.
Jamie

Related

how do i dynamically change my format rendering engine in rails?

My default templating engine is haml, but I would to sometimes change it to erb if i specify a specific parameter?
For example, I am pasting in some html code and would just like to test the code without HAML complaining about its format.
Any idea how to do this?
do something like:
if params[:render_erb]
render 'file.html.erb'
else
render 'file.html.haml'
end
and call the action with ?render_erb=true
or
render "file.html.#{params[:render]}" ir params[:render]
and call it ?render=haml or ?render=erb (or nothing and it will use the default
at the end of the controller's action that you are using
Am I wrong that you simply need to save file as your_file.html.erb instead of your_file.html.haml?
You can use different templates in the same application, and you can use different template engines for views, partials, and layouts, but as far as I know you can't duck in and out of multiple template engines within the same template file.
If you just want to drop some code in using a different template language, then I'd put it in a separate partial. That certainly seems easiest in this particular case.

Where should I put XML Builder code?

I am creating a method to generate an XML document via Ruby Builder.
Where should I put the method that created the XML markup? Should it be a method on the model?
I plan to have the XML document pull from multiple models via associations, so I think I need to have it in the controller or a helper, but I would like some in put on the best place.
If it's practical for you, I'd put it in your views folder. This lets you follow the traditional pattern of "load stuff in the controller; render stuff in the view," and has the extra perk of keeping what's probably a messy and very specific method in its own file and out of the way.
Now, I'm not sure if there's a Ruby Builder template format, but you could always just wrap your code in <%= ... %> and treat it like a regular ERB file - should work about the same.
Hope that helps!

Is it a good idea to create a helper method for this type of scenario?

I have this code in my html.erb at many places.
<div id="left-nav">
<%= render :partial => 'tests/tests_left_menu' %>
</div>
Is it a good idea to create helper method for this type of code ?
How to write this code in helper ?
I see a few good strategies to use in your situation. Pick and choose based on your project's specific requirements.
You can just put div#left-nav and its contents into yet another partial like tests/tests_left_menu_with_wrapper. This saves you a couple of lines.
If you can generalize the cases when the entire segment appears, you can move it into a layout. This way, once you declare the layout for a particular action using the ActionController::Base.layout method, you'll be able to skip writing the entire segment altogether.
You can write a helper, but it's not clear what advantage it confers over simply using content_tag. You're probably better off using partials or layouts.
Personally i don't think there's a need to, and i think it's more like because you are not using other tools like haml to help reduce the number of lines in an erb files
the same code can be achieved in haml in just 1 line:
#left-nav= render :partial => 'tests/tests_left_menu'
hope this helps =)
I suppose if you have that code in many places I'd move the the div into the partial. If you need the flexibility to have tests_left_menu outside of the div I'd still pick two partials over a helper in this scenario. Avoid writing html in Ruby when you can :)

Correct coding convention for embedded code on web page templates

I had come experience with PHP a time ago and now I'm learning to use Ruby on Rails. But one simple question bothered me in both these languages, so I think I can cross-post it to both tags.
As you know, one of the concepts there is that one can embed PHP or Ruby code into web page template. Then these statements are executed and result of its execution is inserted in certain places of the page, marked with "brackets" <%= ... %>.
Or... wait. We program Ruby/PHP, but not HTML. Maybe we should treat template as Ruby/PHP code, into which sometimes HTML markup is inserted? So the process is treated like that HTML are inserted into ruby code into the "brackets" %> ... <%.
These are two different approaches:
HTML page is the primary entity, and it is affected by code execution; or
code is the primary entity, and it is executed, while HTML snippets are inserted in certain places.
This philosophy leads to different possibilities in coding conventions: result of code execution influences the page If we adhere the first insight, then the code would look like this:
<p>
<% (1..10).foreach do |i| %>
Iteration number <strong><%= i %></strong>. <br/>
<% end %>
</p>
But if we stick to the second alternative, the code would be formatted like this:
<%
%><p><%
(1..10).foreach do |i|
%>Iteration number <strong><%
%><%= i %><%
%></strong>. <br/><%
end
%>
How should the concept of templates be construed? What concepts do you, way more experienced Web developers, account for the coding convention?
If this is in your View layer (and it should be), then the HTML is the primary entity. It's the most pertinent part of that layer -- marking up your data to display in meaningful ways to the user.
Even aside from that, your second example is nearly unreadable. I see what you're doing, but it took me a minute to wrap my brain around it. I've also never, ever seen View-layer code like your second example (and I would make it one of my priorities to change it wherever I saw it if it was in a project I was working on).
To be more concise: you're putting the emphasis on the wrong thing. In my opinion, readability trumps just about everything else. The coding style that produces the most readable code is therefore the most superior (ceteris paribus and YMMV, of course).
Maybe you should look into Haml? I don't know if there's a php equivalent, but as far as Rails goes, it's somewhere in between the two schemes. It's not quite code centric. But when used right, all the raw html is prepared programatically.
In short everything is considered text to be directly outputted, unless prefixed with either a %, - or =. Which translate to html-tag, ruby code that doesn't output. Ruby code that does output. Haml then uses whitespacing to nest things properly, much like python does. Raw html outputs untouched but using % to specify a tag handles closing tags.
Sample:
#outer-div
- #items.each do |i|
%span.item
= i
%br
Outputs
<div id="outer-div">
<span class="item">
item
</span>
<br>
</div>
See the haml tutorial for more information.
To answer the central question. The bulk of any page is going to be HTML or raw text. We reduce the bulk of that text with includes and helpers, but it's still there. If there were a truly code centered approach my use of it would depend on the ratio of program logic to html. Personally I'd rather go with the html centered approach.
If you are interested in a code-oriented view, this is something you might try implementing as a pure Ruby DSL:
tag :p, :class => 'iterations-container' do
(1..10).each do |i|
text "Iteration number "
tag :strong { text i }
text "."
tag :br
end
end
Or perhaps instead of tag :p do ... end, you may favor tag.p do ... end.
I recommend doing only very simple logic in your template files. That way designers who can edit HTML can easily edit even those files to alter the layout if need be.

Why shouldn't Helpers have html in them?

I have heard that it's best not to actually have any html in your helpers; my question is, Why not? And furthermore, if you were trying to generate an html list or something like that, how can I avoid actual tags?
Thanks!
-fREW
My advice - if it's small pieces of HTML (a couple of tags) don't worry about it. More than that - think about partials (as pulling strings of html together in a helper is a pain that's what the views are good at).
I regularly include HTML in my helpers (either directly or through calls to Rails methods like link_to). My world has not come crashing down around me. In fact I'd to so far as to say my code is very clean, maintainable and understandable because of it.
Only last night I wrote a link_to_user helper to spits out html with normal link to the user along with the user's icon next to it. I could have done it in a partial, but I think link_to_user is a much cleaner way to handle it.
I don't see that there's anything wrong with it. The majority of the rails helpers generate HTML code (which is their purpose) - to me this implies that's what you're supposed to do yourself.
There is however the ever-present issue of code readability. If you have a helper which just builds a big string of raw HTML, then it's going to be hard to understand. While it's fine to generate HTML in helpers, you should do it using things like content_tag, and render :partial rather than just return %Q(<a href="#{something}">#{text}>)
This isn't a full answer to your question, but you can create html in your tags via the content_tag method. My guess as to why would be cleanliness of code.
Also, content_tag allows you to nest tags in blocks. Check out this blog post on content_tag.
On Rails 3 you can use *html_safe* String method to make your helper methods return html tags that won't be escaped.
As mentioned before, helpers are generally thought to be used as business logic, for doing something that drives view code, but is not view code itself. The most conventional place to put things that generate snippets of view code is a partial. Partials can call a helper if needed, but for the sake of keeping things separated, it's best to keep business in the helper and view in the partial.
Also, bear in mind this is all convention, not hard and fast rules. If there's a good reason to break the convention, do what works best.
I put html into partials usually.
Think about semantics. If you put html in a string, you lose the semantic aspect of it: it becomes a string instead of markup. Very different. For example, you cannot validate a string, but you can validate markup.
The reason I wanna put html in a helper instead of partial (and how I found this thread) is terseness. I would like to be able to write =hr instead of =render 'hr'.
To answer the question I didn't ask ;-) : to un-escape HTML in a helper, try this
def hr
raw '<hr />'
end

Resources