I have a model with several date attributes. I'd like to be able to set and get the values as strings. I over-rode one of the methods (bill_date) like so:
def bill_date_human
date = self.bill_date || Date.today
date.strftime('%b %d, %Y')
end
def bill_date_human=(date_string)
self.bill_date = Date.strptime(date_string, '%b %d, %Y')
end
This performs great for my needs, but I want to do the same thing for several other date attributes... how would I take advantage of method missing so that any date attribute can be set/get like so?
As you already know signature of desired methods it might be better to define them instead of using
method_missing
. You can do it like that (inside you class definition):If listing all date attributes is not a problem this approach is better as you are dealing with regular methods instead of some magic inside
method_missing
.If you want to apply that to all attributes that have names ending with
_date
you can retrieve them like that (inside your class definition):And here's
method_missing
solution (not tested, though the previous one is not tested either):In addition it's nice to override
respond_to?
method and returntrue
for method names, that you handle insidemethod_missing
(in 1.9 you should overriderespond_to_missing?
instead).