Evaluating string templates

ruby, ruby-on-rails

Solution

You can render a string as if it were an erb template. Seeing that you're using this in a rake task you're better off using Erb.new.

template = '<p class="foo"><%=content%></p>'
html = Erb.new(template).result(binding)

Using the ActionController methods originally suggested, involves instantiating an ActionController::Base object and sending render or render_to_string.

Problem

I have a string template as shown below ``` template = '<p class="foo">#{content}</p>' ``` I want to evaluate the template based on current value of the variable called `content`. ``` html = my_eval(template, "Hello World") ``` This is my current approach for this problem: ``` def my_eval template, content "\"#{template.gsub('"', '\"')}\"" # gsub to escape the quotes end ``` Is there a better approach to solving this problem? EDIT I used HTML fragment in the sample code above to demonstrate my scenario. My real scenario has set of XPATH templates in a configuration file. The bind variables in the template are substituted to get a valid XPATH string. I have thought about using ERB, but decided against as it might be a overkill.

Original source