Rails String Interpolation in a string from a database

Raphael Melo picture Raphael Melo · Jul 21, 2011 · Viewed 27.7k times · Source

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.

Answer

Sebastian vom Meer picture Sebastian vom Meer · Apr 29, 2014

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".