Search code examples
ruby-on-railsdesign-patternsdecoratorsti

Rails design pattern: Large number of child models to override specific functions


I have a model that will be called about 50 times to create 50 files with a rake task.

About 90% of the code can be re-used, but I need to override a few of the methods. I was thinking about just inheriting from the original table, but this could lead to around 40-50 models and that didn't feel right:

class Dog 
  def bark
     "woof"
  end
end

class Wolf << Dog
  def bark
     "growl"
  end
end

There's probably around 3-4 methods I will need to override in each model.

The other idea I had was to use the MODULE + EXTEND + SUPER DECORATOR from this post: http://robots.thoughtbot.com/post/14825364877/evaluating-alternative-decorator-implementations-in I.e.

class Dog
  def bark
   "woof"
  end
end

module Wolf
  def bark
   "growl"
  end
end

dog = Dog.new
dog.extend(Wolf)
dog.bark   #growl

And then have 50 modules and extend the proper one at creation time.

So which would be the best option, or is there a better pattern for this situation ?


Solution

  • From the way you describe the dependencies, this actually sounds like a perfect situation for the strategy pattern rather than subclassing or mixing in.

    By subclassing or mixing in, you would be indicating that the specific might call methods of the base, and that it might extend the base API. Furthermore, private methods should always be treated as a potential code smell. If the specific is a strategy object (e.g. a module with module methods) that the base has an instance of and invokes methods of, then that provides the clearest specification of the dependencies you actually have.

    See also: http://en.wikipedia.org/wiki/Composition_over_inheritance, http://c2.com/cgi/wiki?StrategyPattern