String Interpolation Using Rails ActiveRecord Objects

I often find myself wanting to use several attributes of a ActiveRecord object in a string, but have until now been unable to track down exactly how to do that.

Say I have this simple model with a custom method:

class Applicant < ActiveRecord::Base
    def full_name
      [first_name,last_name].reject{ |e| e.empty? }.join ' '
    end
end

If I want to build an email header using that custom method and a few standard attributes, trying this:

subject = "New Application from %{full_name} at %{city}, %{state}" % @applicant

will cough up the error:

ArgumentError: one hash required

Ok, so we need a hash out of our AR object. How about:

subject = "New Application from %{full_name} at %{city}, %{state}" % @applicant.as_json

gives us this:

KeyError: key{full_name} not found

Right! We have to add our custom method manually:

subject = "New Application from %{full_name} at %{city}, %{state}" % @applicant.as_json(methods: :full_name)

Crap! Still failing:

KeyError: key{full_name} not found

Turns out the hash needs to have keys that are symbols. No fear, symbolize_keys to the rescue:

subject = "New Application from %{full_name} at %{city}, %{state}" % @applicant.as_json(methods: :full_name).symbolize_keys

And voila:

"New Application from Nate Beaty at Chicago, IL"

For what seems like such a simple task, this has tripped me up for quite some time, and it’s been difficult to Google exactly what was needed to make this happen.