Sunday, April 17, 2011

Making rails do variable replacement from a db string

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?

From stackoverflow
  • 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.

    Birdman : Good call, I decided to just use a string replace (.sub) instead.
    Gdeglin : Awesome! Much better :-)
  • 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 )
    

0 comments:

Post a Comment