I have methods in all of my models that look like this:
def formatted_start_date
start_date ? start_date.to_s(:date) : nil
end
I would like to have something that automatically writes a method like this for each datetime field in each model, what’s the best way to do this?
-C
I just had to answer this, cos it’s a fun Ruby excercise.
Adding methods to a class can be done many ways, but one of the neatest ways is to use some of the reflection and evaluation features of Ruby.
Create this file in your lib folder as lib/date_methods.rb
Now just include it into any models that need it
When included, the module will look at any date columns and generate the formatted_ methods for you.
Learn how this Ruby stuff works. It’s a lot of fun.
That said, you have to ask yourself if this is necessary. I don’t think it is personally, but again, it was fun to write.
-b-