abrocks
abrocks

Reputation: 171

Ruby Rendering Specific Variable

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?

Upvotes: 2

Views: 131

Answers (1)

Abhishek Patel
Abhishek Patel

Reputation: 138

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.

Upvotes: 1

Related Questions