Rails - why would a model inside RAILS_ROOT/lib not be available in production mode?

◇◆丶佛笑我妖孽 提交于 2019-12-19 03:15:34

问题


I have a class located inside RAILS_ROOT/lib folder, which I use in one of my helpers, and it works great in development.

When I switch to production, the application throws a NameError (uninitialized constant SomeHelper::SomeClass), and I have to load it manually in the helper:

load "#{Rails.root}/lib/some_class.rb"

module SomeHelper
  def some_method
    sc = SomeClass.new
    # blah
  end
end

I was under the impression that everything inside RAILS_ROOT/lib/* should be available all to the app - is there anything I need to configure to make this happen in prod mode? thanks.


回答1:


When you call SomeHelper::SomeClass, Rails' autoloading mechanism will try to load file at lib/some_helper/some_class.rb

Rails won't load everything in lib/*, it will only try to load files when ConstMissing occurs.




回答2:


You might need to check differences between the configuration settings between development and production environment: config/environments/production.rb and config/environments/development.rb.

During the Rails initialization routine, load_plugins() is called which loads all plugins in config.plugin_paths. You need to make sure that your folder lib/ is included, like in

config.plugin_paths = ["#{RAILS_ROOT}/lib/plugins", "#{RAILS_ROOT}/vendor/plugins"]

In addition to config.plugin_paths, you can also name the plugins that should be loaded in config.plugins. If that variable contains :all then all plugins (found) will be loaded.

(By the way: configuration settings equal to either environment should go in config/environment.rb. Any differences between enviroments are due to settings in the respective .rb files.)



来源:https://stackoverflow.com/questions/2872450/rails-why-would-a-model-inside-rails-root-lib-not-be-available-in-production-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!