In rails I have data already in my database. I would like for certain things to be formatted certain ways no matter where it displays in my app. An example might be a social security number. In the database it might be stored as 123456789, but I want to display it as 123-45-6789 anywhere it shows up.
I know that I can format the output using string manipulation, but I wanted to know if there was a better way so that if I were to use,
<%= user.ssn %>
It would automatically get formatted correctly.
Update:
After much, MUCH research on my part, I came across the "lazy" way. You can override the default getter using the following in the User model.
def ssn
read_attribute(:ssn).insert(5, '-').insert(3, '-')
end
My utter ignorance of proper terminology prevented me from finding this more easily. This sort of the is referred to as overriding a method and is discussed in the Rails documentation here.
All that being said I'll be writing a helper method which I originally thought of, but wanted to see if there was an easier way (i.e. less code writing). In the process I learned a lot about ActiveRecord, so my time not wasted. :-)
Other references: