Rails String Interpolation in a string from a database Rails String Interpolation in a string from a database ruby ruby

Rails String Interpolation in a string from a database


I don't see a reason to define custom string helper functions. Ruby offers very nice formatting approaches, e.g.:

"Hello %s" % ['world']

or

"Hello %{subject}" % { subject: 'world' }

Both examples return "Hello world".


If you want

"Hi #{user.name}, ...."

in your database, use single quotes or escape the # with a backslash to keep Ruby from interpolating the #{} stuff right away:

s = 'Hi #{user.name}, ....'s = "Hi \#{user.name}, ...."

Then, later when you want to do the interpolation you could, if you were daring or trusted yourself, use eval:

s   = pull_the_string_from_the_databasemsg = eval '"' + s + '"'

Note that you'll have to turn s into a double quoted string in order for the eval to work. This will work but it isn't the nicest approach and leaves you open to all sorts of strange and confusing errors; it should be okay as long as you (or other trusted people) are writing the strings.

I think you'd be better off with a simple micro-templating system, even something as simple as this:

def fill_in(template, data)  template.gsub(/\{\{(\w+)\}\}/) { data[$1.to_sym] }end#...fill_in('Hi {{user_name}}, ....', :user_name => 'Pancakes')

You could use whatever delimiters you wanted of course, I went with {{...}} because I've been using Mustache.js and Handlebars.js lately. This naive implementation has issues (no in-template formatting options, no delimiter escaping, ...) but it might be enough. If your templates get more complicated then maybe String#% or ERB might work better.


one way I can think of doing this is to have templates stored for example:

"hi name"

then have a function in models that just replaces the template tags (name) with the passed arguments.It can also be User who logged in.

Because this new function will be a part of model, you can use it like just another field of model from anywhere in rails, including the html.erb file.

Hope that helps, let me know if you need more description.