views:

87

answers:

2

I have some code that may just need to be called on a lot of places in the controller and model, where do I put these code in ? And how to call those methods then ?

Thanks

def self.number_of_months(start_date,to_date)
  # Get how many months you want to view from the start months
   (to_date.month - start_date.month) + (to_date.year - start_date.year)  * 12 + 1
end
+2  A: 

If this is always used with one model I'd put it in that model. The self. before your method name means that it's a class method, so if you define the method like this:

class Milestone < ActiveRecord::Base
    def self.number_of_months(start_date,to_date)
      # Get how many months you want to view from the start months
       (to_date.month - start_date.month) + (to_date.year - start_date.year)  * 12 + 1
    end
end

You'd use it by doing this:

Milestone.number_of_months(date1,date2)

Or you might want to put it in the config/initializers directory. For example, create a file called date.rb in the directory containing:

class Date
    def self.number_of_months(start_date,to_date)
      # Get how many months you want to view from the start months
       (to_date.month - start_date.month) + (to_date.year - start_date.year)  * 12 + 1
    end
end

This will be available as a class method to the Date class.

My first answer before I noticed that you mention the method needs to be used in controllers and models. Helpers are used for views, this probably won't be of assistance to you.

This should be a helper method. There's a helper module for each controller, but there's also an application-wide one. That method is fine to put in there, just make sure it's not a class method (remove the self.). If you don't want to add the method to the application helper, you can use the helper declaration in a controller along with the helper module it belongs to i.e. if the method is in date_range_helper.rb use helper :date_range.

dylanfm
+2  A: 

I'd put it in the Date class

class Date
  def months_between(other)
    (month - other.month).abs + 12 * (year - other.year).abs + 1
  end
end
Scott