简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM