When to consider creating your own Ruby module in a Rails app? When to consider creating your own Ruby module in a Rails app? ruby-on-rails ruby-on-rails

When to consider creating your own Ruby module in a Rails app?


1) Any time I'm about to duplicate (or substantially duplicate) a piece of code: "oh, i could just cut/paste into this other controller . . . "

2) Any time I write code that is very obviously going to be reused in the future.

3) Code of substantial size that has a specific purpose, where that purpose is fairly distinct from the main purpose of the controller/model. This is somewhat related to (2), but sometimes code won't get reused but a module helps for organization.


You can place them in the /lib directory and they'll be loaded with your Rails project.

For example, you can view this repo of mine of an old project: lib directory of a Rails project

So for example, I have the following module:

google_charts.rbModule GCharts  class GoogleCharts    def some_method    end  endend

And anywhere in my Rails app, I can access the methods.

So if I were to access it from a controller, I would simply do:

require 'google_charts'GCharts::GoogleCharts.some_method


We use modules for functionality that isn't tied to ActiveRecord models and hasn't been abstracted into a plugin or gem.

A recent example from our production code base is a library for integrating with Campaign Monitor for email list management. The core of the system uses our user model, but the actual interaction with the extenrl service is abstracted through a module that lives in /lib.