2

I have a template which contains various variables for rendering.

Is there a way i can render specific variables in the template without exception.

e.g. template_content = "My name is <%=firstname%>. I live at <%=location%>"

variable_hash = {firstname: "eric"}

Erubis::Eruby.new(template_content).result(variable_hash)  

Expected Output:

   "My name is eric. I live at <%=location%>"   

My use case is render with first variable and get the rendered content.

However when i run above code it gives exception: "undefined local variable or method location"

I am using Erubis for rendering. I am fine with ERB rendering also. Needs to render with ruby script only.

Any way to make it work?

abrocks
  • 171
  • 13
  • What output are you expecting, when location data is missing? Do you want to default to empty string? – Neil Slater Feb 09 '15 at 10:11
  • @NeilSlater expected output: "My name is eric. I live at <%=location%>" – abrocks Feb 09 '15 at 10:12
  • It looks like you want to use this to render content provided by your users. In this case, I have to tell you that this is *NOT* safe, quite the contrary. Using ERB templates, the template author can execute arbitrary ruby code and to everything inside your application, including accessing your database, stealing all your data and wrecking havoc on your server. You definitely do not want to run erb templates provided from your users! – Holger Just Feb 09 '15 at 10:12
  • @HolgerJust the templates are not provided by users. Also there is no db operation going here. Templates are made by our internal devs. I need this to run validations on the partial rendered string. e.g. all links are correctly formatted. I don't have all the variables values at the time of validation. – abrocks Feb 09 '15 at 10:18
  • 1
    As a variant: `variable_hash = {firstname: "eric", location: "<%=location%>"}` ;) – Yevgeniy Anfilofyev Feb 09 '15 at 10:33
  • @YevgeniyAnfilofyev thanks but that doesn't work. There could be unknown variables in the string :( – abrocks Feb 09 '15 at 10:49

1 Answers1

1
module MyModule
  def method_missing(method_name)
    super
    rescue NameError => e
     return method_name
  end
end

eb = Erubis::Eruby.new('My name is <%=firstname%>. I live at <%=location%>')
eb.extend(MyModule)
result = eb.result(:firstname =>'Ab')
puts result

Not sure if this is a good solution, there may be better solutions for this.

Abhishek Patel
  • 138
  • 1
  • 6