In an ActiveRecord model, I want to cast some attributes as specific
custom classes. Example, if I store packed numbers for something like
a phone number, I want them cast as PhoneNumber objects within
ActiveRecord. My PhoneNumber class has various formatters and
extractors and validators. This same idea might apply to SSN, and
even serial numbers, product model numbers etc where various ranges
of characters within the stored string have significant meaning.
I’m reading through ActiveRecord RDocs, and it sounds like I might
want to simply override the default accessors, but that looks like
I’d have to recast the raw value every time with read_attribute. This
would be OK if I was doing a simple conversion of a unit or something
like the RDocs make example of, but these classes are more complex,
and I’d prefer the casting take place one time and remain in effect.
Another alternative is to create a new attribute which is the type
cast version of the raw attribute. So if I have mainPhone as a table
column and native attribute via reflection, I could have main_phone
(or whatever variant) be created as the PhoneNumber class and use the
attr= method to update it and also to drive the update down to
mainPhone. This is the approach I understand the most readily, but I
suspect there’s a better Rails way.
Looking for some idiomatic wisdom…
Much thanks (yet again)
– gw (www.railsdev.ws)