masciugo masciugo - 1 year ago 75
Ruby Question

Override or add methods to already loaded Classes

I'm trying to add functionalities to ActiveSupport::TimeWithZone class addind the following file to my rails project:


class ActiveSupport::TimeWithZone
def in_time_zone_(new_zone ='%a, %d %b %Y %H:%M:%S'))

and in


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

I can use other custom modules in my lib directory but this one seems to be ignored. Any idea why?

enter image description here

Answer Source

Rails loads code for you when you try to use an undefined constant: the const_missing hook rails sets up is called, searches autoload_paths for a file with a name that corresponds to the constant and then requires it.

In your case this code will never be invoked: the TimeWithZone class is loaded during the loading of rails' itself.

You can either put your monkey patch in something that does always get loaded (for example in an initialiser) or require it explicitly from an initialiser.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download