How can i add a method to an existing class in Rai

2019-08-01 08:31发布

问题:

Sorry for my bad english. I have to add a method in Date class in Rails because i want to use my translated day names. So, i tried:

class Date
  def date_of_next(day)
    date  = Date.parse(day)
    delta = date > Date.today ? 0 : 7
    date + delta
  end
end

in config/initializers/date_of_next.rb but when i call Date.date_of_next(day) in my controller i get "no method in Date". How can i do that? And where should i put the file?

回答1:

Putting monkey patched files under initializers is fine (in spite of how "good" monkey patching is itself :)).

You want to change the method definition to following:

class Date
  def self.date_of_next(day)
    date  = parse(day)
    delta = date > today ? 0 : 7
    date + delta
  end
end

Your problem was that you called a singleton method on the object Date, whereas it did not have such method defined.



回答2:

As Andrey Deineko points out in his comment (and now answer), you wrote an instance method but called a class method. Try:

class Date
  def self.date_of_next(day)
    date  = Date.parse(day)
    delta = date > Date.today ? 0 : 7
    date + delta
  end
end

The other (and probably better) way would be more object oriented with an instance method:

class Date
  def date_of_next
    delta = self > Date.today ? 0 : 7
    self + delta
  end
end

day.date_of_next    # you might want to pick a better name

One more hint: monkey patching (extending an existing class in such a way) is not the best solution on the longer run. You might want to switch to different patterns some day.