I am writing a Ruby script that will generate a large flat HTML menu for my website, I could generate this menu on the fly each time a page loads, but I think doing so is a waste of resources, especially as this will almost never need to change.
I want to effectively do the following (in semi-sudocode):
part_of_my_menu = eval %{
<script type="text/javascript">
var mapper = new Array();
<% parent_categories.each_with_index do |parent_category,i| -%>
mapper["#{parent_category.name}"] = <%= i -%>;
<% end -%>
</script&g开发者_Python百科t;
}
and then be able to write the part_of_my_menu string variable to a HTML file (this I can do).
I know this is not how eval works in Ruby but does anyone know how to achieve this same "wrapper" functionality?
(fyi - the code I want to wrap with my "eval" function is much longer than this, I've only posted a very small snippet to illustrate what I am trying to achieve)
Thanks!
ERB is part of the standard library so you could do things like this:
tmpl = %q{<script type="text/javascript">...</script>}
erb = ERB.new(tmpl)
parent_categories = [ ... ]
part_of_my_menu = erb.result
The ERB documentation contains some good examples of how to use it.
You don't need a hand rolled eval
construction, you can use standard existing libraries and your existing knowledge.
You might be interested in the dom gem that I have developed. You can generate HTML strings like this:
require "dom"
["foo".dom(:span, class: "bold"), "bar"].dom(:div).dom(:body).dom(:html)
# => "<html><body><div><span class=\"bold\">foo</span>bar</div></body></html>"
精彩评论