Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global methods in ruby on rails models

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

like image 637
Chris Drappier Avatar asked May 14 '09 14:05

Chris Drappier


1 Answers

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.select do |k| 
                  klass.columns_hash[k].type == :date
                end


    # 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 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-

like image 97
Brian Hogan Avatar answered Oct 05 '22 07:10

Brian Hogan