Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails extending Date class

I have created a file lib/ext/date.rb which extends the Date class with a method.

class Date
  def self.next_(weekday_string)
    // code here
  end
end

In my application.rb file I autoload everything in this ext folder

config.autoload_paths << "#{Rails.root}/lib/ext"

But I keep getting the error undefined method next_ for Date:Class

Calling this method from within the console works fine

load 'lib/ext/date.rb'; Date.next_('wednesday')
=> Wed, 07 Oct 2015

And yes, the server has been restarted before trying to use this extended method.

like image 340
Cjmarkham Avatar asked Aug 20 '26 11:08

Cjmarkham


1 Answers

I guess, your understanding of Rails autoload mechanism is fuzzy.

autoload_paths is used when rails tries to resolve undefined constant. Say, you access a User for the first time. No such class is loaded, so rails will look in its autoload paths and try find User there.

Your case is different. Date is certain to be present (as it is a system class). And thus rails will have no reason to access files in autoload paths.

Solution:

load the files explicitly. For example, in an initializer

# 00_monkey_patching.rb
Dir["#{Rails.root}/lib/monkey_patching/*.rb"].each do |file|
  require file
end
like image 136
Sergio Tulentsev Avatar answered Aug 23 '26 06:08

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!