0

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?

1
  • Are people able to enter any data into this field such as system("rm -rf *")? not good. Commented Mar 31, 2009 at 5:42

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good call, I decided to just use a string replace (.sub) instead.
1

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 )       

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.