Formatting data in Rails Models - Part 2
November 11th, 2006
More advanced topics regarding the model_formatter plugin for Rails.
In Part 1, we learned about setting up the model_formatter to format and un-format attributes as they came in and out of the model. We saw how you could use some simple methods formatted_weight and formatted_weight= to get and set the formatted attributes. In this article, I’ll show you how to use more of the generated methods for more advanced usage.
Update – r5826 changes the default names of the formatters to use the format attribute name. (article revised)
We already know we can do things like the following to our Widget instance:
>> widget.weight = 1000
=> 1000
>> widget.formatted_weight
=> 1,000
>> widget.formatted_weight = '1,100'
=> '1,100'
>> widget.weight
=> 1100
In working on the project this was extracted from, we typically need to do things which access the same formatters, but not necessarily through an instantiated object. When the format_column method accepts our :as => :integer option, it creates an instance of the integer formatter. If you’ve specified a Proc pair or a block, you still get the same benefits, since it will wrap your Procs or block and expose them in a similar way, using (in our :to and :from, or block custom example) a CustomFormatWeight class. With the block, you get the added benefit of optionally adding an initialize method. In any case, you can access this formatter class in the following way:
>> Widget.formatted_weight_formatter 1000
=> 1,000
>> Widget.formatted_weight_unformatter '1,100'
=> 1100
You can also access the options passed to the formatter directly, which can be very helpful to piggy-back meta attributes with an attribute. See the :display_size option:
>> Widget.formatted_weight_formatting_options
=> {:to=>nil, :from=>nil, :options=>{},
:prefix=>"formatted_", :as=>:integer, :display_size => '12pt',
:formatter=>#<Formatters::FormatInteger:0x2601110 @delimiter=",">,
:formatted_attr=>"formatted_weight", :attr=>"weight"}
Hope some of this helps getting the feet wet with the formatter. This has been very useful for me in projects I’m working on – so hopefully you’ll feel the same way too. As always, critque away ;)
Leave a Reply