Reputation: 869
I have a string in a db that contains a local variable reference and I want Ruby to parse and replace it.
For example, the string in the db is "Hello #{classname.name}"
and it is stored in classname.description
and my code reads:
<%=h @classname.description %>
Put that just prints the exact value from the db:
Hello #{name}
and not the (assume classname.name
is Bob):
Hello Bob
How do I get Ruby to parse the string from the db?
Upvotes: 0
Views: 3054
Reputation: 3147
Why don't you use a safe template engine like Liquid, to get around the eval problem?
template_string = "Hello {{name}}" #actually get from database
template = Liquid::Template.parse(template_string) #compile template
name = 'Bob'
text = template.render( 'name' => name )
Upvotes: 1
Reputation: 12618
You can use eval()
to do this. For example:
>> a = {:name => 'bob'}
=> {:name=>"bob"}
>> eval('"Hello #{a[:name]}"')
=> "Hello bob"
However, what you are doing can be very dangerous and is almost never necessary. I can not be sure that this is or isn't the right way to do things for your project, but in general storing code to be executed in your database is bad practice.
Upvotes: 1