Where to put this code in a Rails web application?

Do I have code that might just be needed in many places in the controller and model, where do I paste this code? And what are these methods called?

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
+3
source share
2 answers

If it is always used with one model, I would put it in this model. self.in front of the method name means that it is a class method, so if you define a method as follows:

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 would use it by following these steps:

Milestone.number_of_months(date1,date2)

Or you can put it in a directory config/initializers. For example, create a file with a name date.rbin a 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 for the Date class.

, , , . , , , .

. , . , , , ( self.). , helper , , .. date_range_helper.rb, helper :date_range.

+2

Date

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

Source: https://habr.com/ru/post/1709658/


All Articles