1

I'm working on my first Ruby on Rails project and I am now faced with a design dilemma. I'm no professional programmer so I may be missing some pretty basic stuff. Please bear with me.

My project is a simulator of electoral systems. I have (among others) these models

class Town < ActiveRecord::Base
  attr_accessible :census, :name
  has_many :results
  has_many :parties, :through => :results
  belongs_to :region
end

class Party < ActiveRecord::Base
  attr_accessible :acronym, :name
  has_many :results
  has_many :towns, :through => :results
end

class Result < ActiveRecord::Base
  attr_accessible :party, :town, :votes, :year
  belongs_to :town
  belongs_to :party
end

Both classes Town and Party will have a method seats(), and the algorithm for computing seats (from :census or from :votes, resp.) will be essentially the same. I would like to be able to code the algorithms in a way that can be applied to either.

I have thought of various solutions:

  • Code a generic function and pass it a pointer to the desired class. This has the problem that what in one case is :census in the other case is :votes, I don't know how easy it is to manage this in RoR. Can I pass a pointer to the column as well? It doesn't sound too Rubyish.
  • Inherit from a common class where the algorithms are defined. Then I'd lose the ActiveRecord functionality which is actually very handy. Or would I?
  • Create a generic algorithm and feed it raw arrays of data from the class-specific methods accordingly. This means that I have to code the data interface for each class separately.

I'd like the solution to be scalable, i.e., someday I'd like it to work for "regions" which will be collections of towns, and for "coalitions" which will be collections of parties...

Would you implement any of these options? What are the pros/cons of each of them? Is there a standard approach to this problem?

Alex Monras
  • 198
  • 2
  • 10
  • http://stackoverflow.com/questions/1282864/ruby-inheritance-vs-mixins – tokland Apr 14 '13 at 18:24
  • so, there's the option of a mixin, didn't know that. Thx for the comment. Is there a way to have a module which uses :census or :votes accordingly? – Alex Monras Apr 17 '13 at 17:20
  • Yes, move all common methods to a module, and `include` them, that's standard practice. Ideally, code in modules should be as agnostic and modular as possible, so as to create as less coupling as possible. – tokland Apr 17 '13 at 18:26

0 Answers0