views:

183

answers:

2

What are the advantages and disadvantages of creating a module like:

module Section
  def self.included(base)
    base.class_eval do
      has_many :books
    end
  end

  def ensure_books
    return false if books <= 0
  end
end

...where ActiveRecord methods are used in the module instead of directly on the class(es) they belong to?

Should modules be used for methods like this?

A: 

This code can be shared by models (classes).

Chandra Patni
+1  A: 

The most obvious advantage is that you can take functionality that is shared and put it into a single place. This is just a general advantage of keeping your code organized and modularized (no pun intended) – and you should, of course, do that

Using Active Record methods does not make these Modules special in any way.

The most obvious disadvantage is that your code, as written, is a little more complex. You can't use validates_presence_of in a module directly because it does not inherit from ActiveRecord::Base. (Rails 3 is supposed to make it easier to selectively extend your own classes/modules with bits of ActiveRecord-Functionality

Instead, you need to call the Active-Record-Methods on your model class when your model is included:

module FooHelper
  def self.included(other)
    other.send(:has_many, :foos)
  end
end

So the prime disadvantage is that your code gets a little harder to read.

If you are just breaking up a single class into separate parts and don't need to reuse the code somewhere else, you could use the concerned_with-pattern which works by reopening classes.

On the other hand, If you need more functionality, like configuration parameters for your extension, consider writing a plugin

levinalex
Would you be concerned with having relationships on models hidden away into modules?
Laz
in general: no, if you get the naming right so that it is obvious what the module does. Having functionality split into logically named, well tested parts is much better than repeating the same code all over the place or having all the code in one giant file
levinalex