The Ruby Mix

Page

At my first job fresh out of college I was doing mostly C++ programming. I remember that one thing I had a love hate relationship was with Multiple inheritance. On the one hand there were many situations where it was the perfect fit for my application, but due to increased complexity and ambiguity in most situations, I tended to design without. Now that I do programming in Ruby, mixins have given me the power of multiple inheritance without the complexity.

What exactly are Mixins?

A module that is included within the definition of another module or class using the include method. When a module is included within a class, the module’s constants, class variables, and instance methods are bundled into an anonymous proxy superclass for that class.

Let’s say we have a Calculations module that does calculations of rows on a specified column in the database.

module Calculations
  def min(column_name)
    "Minimum value calculated for #{column_name}"
  end
  def max(column_name)
     "Maximum value calculated for #{column_name}"
  end
  def total(column_name)
     "Total value calculated for #{column_name}"
  end
end

We also have an Expense class that inherits from ActiveRecord::Base.

class Expense < ActiveRecord::Base
end

In our Expense class we would like the ability to perform calculations on our expenses. To achieve this we need to mixin the Calculations module (for this example we are ignoring the fact that ActiveRecord::Base already includes a Calculations module):

class Expense < ActiveRecord::Base
  include Calculations
end

We can now access the calculation methods through an Expense instance, or in our case expenses collection:

@expenses = Expense.find(:all)
@total = @expenses.total :amount
@max = @expenses.max :amount
@min = @expenses.min :amount

With Ruby mixins we have a very simple and flexible way to support a multiple inheritance object model.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s