Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 autoload

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 ?

like image 264
daniel Avatar asked Nov 01 '10 23:11

daniel


People also ask

How do you autoload in rails?

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.

What is autoload in Ruby?

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.

What is Zeitwerk?

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).

What are Initializers in rails?

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.


1 Answers

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.

like image 193
Damien MATHIEU Avatar answered Sep 17 '22 21:09

Damien MATHIEU