I want to add a library that I wrote to a Rails app (and to other Rails apps later). I tried putting it in /lib
which seemed logical...
[RAILS_ROOT]/lib/my_lib/the_main_file.rb
[RAILS_ROOT]/lib/my_lib/some_other_file.rb
The开发者_JAVA百科n...
require 'my_lib/the_main_file'
That works fine.
But is that a great way to do it?
Now I have to put that require
everywhere I want to call the library.
I thought about putting the require
in an initializer but that seems kind of weird.
What do people usually do about this?
Using an initializer may look weird when you have a single file to include, but sometimes I have many files that I want to add, and end up using an intializer that only includes stuff. It's actually pretty neat.
I'm not sure about the "best practices"(tm) or anything, but we do a similar thing for our project as well. The library is in lib
, and the require
in an initializer (app_config.rb
in our case). This seems like a good way to do things, and hasn't bitten us in the butt thus far :) Hope that helps.
I usually wrap up my stuff in classes. If you add config.autoload_paths += %W(#{config.root}/lib)
to your application.rb
then any reference to a missing constant will result in an attempt to autoload it, i.e just using MyClass.new
will make it try to load `lib/my_class.rb'.
Have a look at Best way to load module/class from lib folder in Rails 3?
精彩评论