Rails 3 autoload

后端 未结 4 1669
面向向阳花
面向向阳花 2020-12-01 09:45

I have a class ConstData:

class ConstData

  US_CITIES = [\'miami\', \'new york\']

  EUROPERN_CITIES = [\'madrid\', \'london\']

end

Its s

相关标签:
4条回答
  • 2020-12-01 10:11

    config.autoload_paths did not work for me. I solved it by putting the following in ApplicationController:

    Dir["lib/**/*.rb"].each do |path|
      require_dependency path
    end
    
    0 讨论(0)
  • 2020-12-01 10:14

    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.

    0 讨论(0)
  • 2020-12-01 10:26

    The reason autoload_paths didn't work for you and you were forced to do:

    Dir["lib/**/*.rb"].each do |path|
      require_dependency path
    end
    

    is because you forgot to namespace your class.

    lib/awesome/stuffs.rb should contain a class/module like this:

    class/module Awesome::Stuffs
    ....
    

    but you had:

    class/module Stuffs
    ....
    

    Rails can only autoload classes and modules whose name matches it's file path and file name.

    :)

    0 讨论(0)
  • 2020-12-01 10:33

    Follow the solution for lib dir be autoloaded:

    Remove config.threadsafe! from development.rb and production.rb;

    Add in config/application.rb:

    config.autoload_paths += %W(#{config.root}/lib)
    config.threadsafe!
    config.dependency_loading = true
    
    0 讨论(0)
提交回复
热议问题