Subfolders in lib

2019-02-17 14:32发布

I have a module called user_searches. It performs some searches that aren't core to the user model, thus, why I'm putting the responsibility somewhere else. I want to organize all my models like this that perform non-core user functions in a lib subfolder called user. Right now to include the module's methods in the User model I have to put...

require 'user/user_searches'

class User < ActiveRecord::Base

  include UserSearches

end

...I don't need the require if the file is directly in the lib folder, but do if it's in the subfolder. What do I have to do so I don't need the require?

2条回答
叛逆
2楼-- · 2019-02-17 14:39

You could put the necessary require lines into lib/user.rb that way, all requirements are loaded recursively on application launch.

Alternatively, you could put something like this into an initializer:

# put into config/initializers/load_lib.rb
Dir["#{RAILS_ROOT}/lib/**/*.rb"].each { |f| require(f) }

It will require all ruby files in your lib folder. You just have to make sure if this is really what you want :)

查看更多
成全新的幸福
3楼-- · 2019-02-17 14:59

This is works that cause

in file rails-2.2.2/lib/initializer.rb in method default_load_paths initialized to load path just the lib folder without subdirectories, to solve this you can edit your project ` environment.rb config file and push into config.load_path array all subdirs.

查看更多
登录 后发表回答