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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With