Ruby mixins are powerful

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.

A reminder of Ruby’s mixins powers:

I loosely modeled the BigInteger and Number classes after the Java versions. The BigInteger class defines one constructor and directly inherits one method from the Number base class. To mix in the methods implemented in the Stringify and Math modules with the BigInteger class you will note the usage of the include and extend methods, respectively.

# Create a new object
bigint1 = BigInteger.new(10)
# Call a method inherited from the base class
puts bigint1.intValue # –> 10

The extend method will mix a module’s methods at the class level. The method defined in the Math module can be used as a class/static method.

# Call class method extended from Math
bigint2 = BigInteger.add(-2, 4)
puts bigint2.intValue # –> 2

The include method will mix a module’s methods at the instance level, meaning that the methods will become instance methods. The method defined in the Stringify module can be used as an instance method.

# Call a method included from Stringify
puts bigint2.stringify # –> ‘Two’

There is another use of the extend method. You can enhance an object instance by mixing it with a module at run time! This is a powerful feature. Let me create a module that will be used to extend an object, changing its responsibilities at runtime.

# Format a numeric value as a currency
module CurrencyFormatter
def format
“$#{@value}”
end
end

To mix an object instance with a module you can do the following:

# Add the module methods to
# this object instance, only!
bigint2.extend CurrencyFormatter
puts bigint2.format # –> ‘$2’

Calling the extend method on an an instance will only extend that one object, objects of the same class will not be extended with the new functionality.

puts bigint1.format # will generate an error

Post external references

  1. 1
    http://juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/
Source