Rails String Interpolation in a string from a database

Viewed 30567

So here is my problem.

I want to retrieve a string stored in a model and at runtime change a part of it using a variable from the rails application. Here is an example:

I have a Message model, which I use to store several unique messages. So different users have the same message, but I want to be able to show their name in the middle of the message, e.g.,

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

I tried to store exactly that in the database but it gets escaped before showing in the view or gets interpolated when storing in the database, via the rails console.

Thanks in advance.

5 Answers

gsub is very powerful in Ruby.

It takes a hash as a second argument so you can supply it with a whitelist of keys to replace like that:

template = <<~STR
Hello %{user_email}!

You have %{user_voices_count} votes!

Greetings from the system
STR

template.gsub(/%{.*?}/, {
  "%{user_email}" => 'schmijos@example.com',
  "%{user_voices_count}" => 5,
  "%{release_distributable_total}" => 131,
  "%{entitlement_value}" => 2,
})

Compared to ERB it's secure. And it doesn't complain about single % and unused or inexistent keys like string interpolation with %(sprintf) does.

Related