I have some behavior in my controller that I pulled out into a module in order to test better and re-use it in a few places. Two questions about this:
- Where is a good place to put my modules? They need to run in order to be available to the controllers, so I was thinking the
config/initializers/
directory. That seems a little suspect to me though.lib/
? - How do I ensure the code gets run so the modules are available to
include
in my controllers?
Thank you kindly sirs.
1) I like to put: my class extentions under app/extentions my modules under /app/mixins my services under /app/services
2) You can configure your application to load all of these in config/application.rb: class extentions should be required right way and the mixins and services can be added to your autoload path
(I'm using rails 3)
lib/
is an excellent place for modules; much better thanconfig/initializers/
--at least in my opinion. If it's several modules, or one large one, you can also consider making it a plugin and placing it invendor/plugins
.If you put it in
lib/
, you'll need to manuallyrequire
the file. Rails, by default, does not autoload files in thelib/
directory. You can place the require in one of your config files.I usually put my additional autoloads in
config/application.rb
. Something like this should do the trick (assuming that your.rb
file is in a directory calledlib/my_module
):You have to make sure that your module is an actual
module
and not aclass
. Then, you can simply include it:Try putting controller specific modules in
app/controllers
. Norequire
required.