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?
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_ofin a module directly because it does not inherit fromActiveRecord::Base. (Rails 3 is supposed to make it easier to selectively extend your own classes/modules with bits of ActiveRecord-FunctionalityInstead, you need to call the Active-Record-Methods on your model class when your model is included:
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