When and where do I require files in a rails application?

前端 未结 5 1618
半阙折子戏
半阙折子戏 2021-02-03 22:00

Let\'s say I have I have the following file in my lib directory of my rails application:

#lib/proxy.rb
module SomeService
  class ServiceProxy
    def do_somethi         


        
相关标签:
5条回答
  • 2021-02-03 22:35

    Rails will auto add /lib /vendor /app this dir into autoload path. When you need some constants in it, you need to require the specific file. And you don't need to require it the second time, because it would be useless.

    0 讨论(0)
  • 2021-02-03 22:37

    Also note that some environment.rb's come with these comments:

    Rails::Initializer.run do |config|
      # Add additional load paths for your own custom dirs
      # config.load_paths += %W( #{RAILS_ROOT}/extras )
      config.load_paths << "#{RAILS_ROOT}/app/models/some_model_group"
      config.load_paths << "#{RAILS_ROOT}/lib"
    end
    
    0 讨论(0)
  • 2021-02-03 22:43

    This is a helpful post about this issue.

    In short, Rails autoloads classes in your lib directory only if they follow the proper naming conventions.

    0 讨论(0)
  • 2021-02-03 22:43

    Have you tried removing it from the first model as well? I believe Rails will automatically load any files you have in your lib directory without you ever having to require them explicitly.

    0 讨论(0)
  • 2021-02-03 22:44

    I would generally place that require statement in a config/initalizer file, e.g. config/initializers/load_proxy.rb

    0 讨论(0)
提交回复
热议问题