Model Using Modules in Rails Application

Kevin Sylvestre picture Kevin Sylvestre · Sep 23, 2010 · Viewed 10.3k times · Source

I have a model that requires loading external data from an auxiliary source. A number of web services exist that my model can fetch the data from (swappable), but I don't want to create code that will make it difficult to change services (costs significantly differ based on variable and fixed usage and it is likely changing will be required).

I would like to create a driver to perform the interaction (and then create further custom drivers if the service requires switching). Unfortunately, due to the tight coupling of the driver and model, it does not makes sense to extract the code into a plugin or gem. I have extracted all the code into a module (see example), and currently have the code declared above my model.

module Synchronize
  def refresh
    self.attributes = ...
    self.save
  end
end

class Data < ActiveRecord::Base
  include Synchronize
end

Does Rails (3.0.0) have a convention for storing modules tightly coupled with models? Should I be using a plugin to do this? Is this associated with the 'app/helpers' directory? If not, where is the most appropriate place to store the code? Thanks!

Answer

Sidane picture Sidane · Sep 28, 2010

You are correct that if the module is tightly coupled to that specific model then it's not a good candidate for a gem/plugin.

app/helpers/ is for view helper methods and shouldn't contain modules that are solely for mixing into models.

One place you could put the module is within lib/. This is for code that doesn't really fit anywhere within app/ and is often the initial home of loosely coupled code before it is moved to a plugin (but that isn't a hard and fast rule). However, since your module is tightly coupled to your model, lib/ may not be the best place for it.

I know that 37signals (and others) use the concept of 'concerns' as a way of keeping related model code organised in modules. This is implemented by creating app/concerns/ and putting the modules in there. That directory is then added to the app's load path in config/application.rb (config/environment.rb for Rails 2) with:

config.load_paths += %W(#{Rails.root}/app/concerns)

The module can then be mixed into the model as normal.

Here's the original blog post about this by Jamis Buck - http://weblog.jamisbuck.org/2007/1/17/concerns-in-activerecord

Another variation of this which I personally prefer, although it doesn't involve modules, uses this plugin: http://github.com/jakehow/concerned_with

Hope that helps.