global methods in ruby on rails models

前端 未结 3 1003
孤城傲影
孤城傲影 2021-02-04 18:33

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

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 19:28

    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-

提交回复
热议问题