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
module DateMethods
def self.included(klass)
# get all dates
# Loop through the class's column names
# then determine if each column is of the :date type.
fields = klass.column_names.collect do |k|
k if klass.columns_hash[k].type == :date
end
# collect throws in empty entries into the
# array if we don't meet the condition in the loop
# so we should remove those nils.
fields.compact! # removes nils
# for each of the fields we'll use class_eval to
# define the methods.
fields.each do |field|
klass.class_eval <<-EOF
def formatted_#{field}
#{field} ? #{field}.to_s(:date) : nil
end
EOF
end
end
end
Now just include it into any models that need it
class CourseSection < ActiveRecord::Base
include DateMethods
end
When included, the modeule 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-