A while ago I wrote a small library to handle string interpolation in a Rails application. The library allows you to safely allow users to insert variables into strings they provide to you. For example, if you allow your users to write outgoing e-mails, you may want to allow them to insert appropriately formatted data into these.

Hello {{user.first_name}}, Thanks for buying {{product.name}} from our store. If you have any questions or issues with it, please don't hesitate to contact us at {{store.email_address}}. Many thanks, {{store.name}}

My Florrick gem allows you to easily expose data in your models to your users. Continuing with the example above, you may configure your Person model as follows:

class Person < ActiveRecord::Base

  belongs_to :parent, :class_name => 'Person'

  florrick do
    string :first_name, :last_name, :full_name
    relationship :parent

  def full_name
    "#{first_name} #{last_name}"


Once you’ve configured which attributes/methods you’d like to expose, you can then pass a string through it.

string = "Hello {{person.first_name}}"
final_string = Florrick.convert(string, :person => person)

We find this technique to be really good as it provides a central point to expose variables across any number of models. What’s more, you can expose relationships through Florrick too. For example, if one person has a parent relationship, you can access that too if you list the relationship as shown above.



As well as being able to insert strings straight from your model, you can also pass them through various formatters which allow them to be adjusted. This might be useful if you want to format dates and times.

{{person.date_of_birth.long_date}}  #=> "Sunday 23rd October 1960"
{{person.date_of_birth.ddmmyyyy}}   #=> "23/10/1960"

There a number of built-in formatters but you can also register your own formatters. Full details can be found in the docs.

This post is just a quick intro the library and there is more information on GitHub.

Tell us how you feel about this post?