I have a class ConstData:
class ConstData
US_CITIES = ['miami', 'new york']
EUROPERN_CITIES = ['madrid', 'london']
end
Its stored under /lib/const_data.rb
The idea is that inside a model, controller or view I can do:
ConstData::US_CITIES
to get the US_CITIES etc
Rails should load this class automatically, I got this from: http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/662abfd1df9b2612?hl=en
However this does not work. Can anyone explain me how to accomplish this ?
Rails automatically reloads classes and modules if application files in the autoload paths change. More precisely, if the web server is running and application files have been modified, Rails unloads all autoloaded constants managed by the main autoloader just before the next request is processed.
Ruby has an in-built module autoload, which comes into action whenever a specific module or a class is accessed or called upon from the parent or calling class or module. Upon receiving a call, this module registers the corresponding file path to the called module.
Zeitwerk is an efficient and thread-safe code loader for Ruby. Given a conventional file structure, Zeitwerk is able to load your project's classes and modules on demand (autoloading), or upfront (eager loading).
An initializer is any file of ruby code stored under /config/initializers in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and plugins are loaded.
The post @daniel refers to is from 2008. Rails has changed since then.
In fact, quite recently. Rails3 doesn't load the lib/ directory automatically.
You can reactivate it quite easily though. Open config/application.rb
And add, in the config (in the Application
class) the followin :
config.autoload_paths += %W(#{config.root}/lib)
Then your lib/ dir will be autoloaded.
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