InFormat

Easily add custom getter and setter filters for attributes on ActiveRecord objects. These can be useful if you wish to scrub data before it hits your datastore and/or provide uniformity when reading.

Requirements

For Ruby 1.9.0 and greater. Tested with Rails 3.1+ using ActiveRecord. It should work with any ORM that provides a hash syntax for accessing attributes in Models (please let me know if you have success/failures with other ORMs).

Installation

Add the requirement to your Gemfile

gem "in_format"

That's it if using ActiveRecord. If using a different ORM you will need to extend InFormat on the models, add an initializer or shoehorn it in some other way.

Usage

Invoke in_format, phone_format or ssn_format in your Model for attributes you wish to process.

in_format

The in_format method is the most general and accepts a getter and/or a setter.

Under the hood these create setters/getters and process the value through the supplied Proc/lambda and set/read the value using the hash syntax (self[:attribute_name]).

There is an use_accessor option which will override getter/setter methods matching the attribute. This can be useful if you want to combine in_format with attr_accessor or gems like attr_encrypted (just be sure that the overridden methods exist before using in_format).

You can access the original getter by passing true to the new one (assuming you supplied a getter).

Reccomendations

If you have getters/setters you would like to re-use across many attributes or classes I would stick em all in a (well-tested) module and keep an eye out for edge cases. You can also use in_format as the base for your own custom methods like phone_format, etc.