views:

154

answers:

1

I've got the following problem: I have rhtml (html minced together with ruby inside <% %> and <%= %> tags) stored in a database which I want to render. The information is acquired through a query. I need to be able to evaluate the information I get from the database as though as it was normal content inside the .erb-file. What I currently have:

<% @mymods.each do |mod| %>
<%=  render_text(mod["html"])%>
<% end %>

Where mod["html"] is the variable containing the rhtml-code and @mymods an array of objects from the query. I have currently no idea what function I should use (render_text does, of course, not work).

Help is greatly appreciated.

/TZer0

+2  A: 

You can use the ERB object to render text without the text being in a file.
Just pass the text with the <%= %> tags. You could put something like the following as an application_helper function.

def render_erb_text(text, args={})
   b = binding
   template = ERB.new(text, 0, "%<>")
   template.result(b)
end

And then in your template

<%=  render_erb_text("<%= %w(hi how are you).join(' - ') %>")%>

You might also consider rendering the text in your controller as you can handle any render errors better there than during view evaluation.

Take a look at the ERB documentation for more information regarding variable binding etc.

I'm not familiar with the details of how this works under the covers, but there could be some serious risk in running this code on bad or malicious database data. Evaluating ruby code from user input or any un-vetted source should be done very carefully, if at all.

danivovich
Thanks for the help, this worked. Sorry for not being able to upvote you for this. I don't have 15 rep yet ;)
TZer0