AlexBeginner AlexBeginner - 10 days ago 6
Ruby Question

How can i add a method to an existing class in Rails 5?

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?

Answer

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.