I create 'getters' or 'setters' and then just use read_attribute,
write_attribute when necessary.
Here is one example. I want to take any of the following string for
gender: M, m, Male, Female, f, F .... etc..
So I take care of the logic before I store it. I also want to take
the chance to store it in a consistent way (translating M to Male).
#
# Custom writer to make sure we store the
# gender information consistently. We
# store: 'Male', 'Female', or 'Unknown'
#
def gender=(gender_string)
case gender_string
when /^[M|m](ale)*$/: write_attribute(:gender, 'Male')
when /^[F|f](emale)*$/: write_attribute(:gender, 'Female')
when /^[U|u](nknown)*$/: write_attribute(:gender, 'Unknown')
# Let the validations catch anything else.
else write_attribute(:gender, gender_string)
end
end
:gender is the field name in the database. This provides a hook if
you will that gives you access to the element before it's stored.
Validations will pick up _after_ this is run. Therefore, I allow
validations to kick in for the 'else' clause. I've combined this with
the following validator:
validates_inclusion_of :gender, :in => %w{ Male Female Unknown }
Hope this helps.
-Joe
-Joe
_______________
Joe O'Brien, artisan
EdgeCase
theedgecase.com