Best way to load module/class from lib folder in Rails 3?

后端 未结 12 1728
别跟我提以往
别跟我提以往 2020-11-22 11:56

Since the latest Rails 3 release is not auto-loading modules and classes from lib anymore, what would be the best way to load them?

From github:

相关标签:
12条回答
  • 2020-11-22 12:17

    As of Rails 5, it is recommended to put the lib folder under app directory or instead create other meaningful name spaces for the folder as services , presenters, features etc and put it under app directory for auto loading by rails.

    Please check this GitHub Discussion Link as well.

    0 讨论(0)
  • 2020-11-22 12:19

    config.autoload_paths does not work for me. I solve it in other way

    Ruby on rails 3 do not automatic reload (autoload) code from /lib folder. I solve it by putting inside ApplicationController

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

    If only certain files need access to the modules in lib, just add a require statement to the files that need it. For example, if one model needs to access one module, add:

    require 'mymodule'
    

    at the top of the model.rb file.

    0 讨论(0)
  • 2020-11-22 12:26

    Spell the filename correctly.

    Seriously. I battled with a class for an hour because the class was Governance::ArchitectureBoard and the file was in lib/governance/architecture_baord.rb (transposed O and A in "board")

    Seems obvious in retrospect, but it was the devil tracking that down. If the class is not defined in the file that Rails expects it to be in based on munging the class name, it is simply not going to find it.

    0 讨论(0)
  • 2020-11-22 12:29

    Very similar, but I think this is a little more elegant:

    config.autoload_paths += Dir["#{config.root}/lib", "#{config.root}/lib/**/"]
    
    0 讨论(0)
  • 2020-11-22 12:30

    I had the same problem. Here is how I solved it. The solution loads the lib directory and all the subdirectories (not only the direct). Of course you can use this for all directories.

    # application.rb
    config.autoload_paths += %W(#{config.root}/lib)
    config.autoload_paths += Dir["#{config.root}/lib/**/"]
    
    0 讨论(0)
提交回复
热议问题