Where to put Rails modules

by Jason Swett,

Short answer: put your modules in /lib.

If you’d like more guidance than that, read on.

How to define a module at all

You can define a module like this:

When you include that module in a class, you can use the hello function in the class from which you included the module. I’ll show you exactly how that works in a second.

How to include a module in, say, an ActiveRecord model

You can include a module in a class in your Rails project by using the include keyword followed by the name of your module.

Now you should be able to do Customer.new.hello and get “hello” as a result.

Hey, that didn’t work!

Right. In addition to defining the module you also have to include the module (include in the “including a file” sense) in your project.

Files under /lib are not by default autoloaded into Rails. I know this because the docs say:

config.autoload_paths accepts an array of paths from which Rails will autoload constants. Default is all directories under app.

“All directories under app” does not, of course, include lib. We have to add it manually, which can be done in the following way:

It should work now

Now if you go back and follow those first steps again, it should work.

And if you want to do nested modules, you can do this:

And then this:




Leave a Reply

Your email address will not be published. Required fields are marked *