Ruby:Mixin
lastmod 2018-08-17created 2015-12-102 edits
Ruby has something called a Module, which is similar to a Class. Like a Class, a Module can contain methods, constants, modules, and classes. Unlike a Class, however, you cannot inherit from a module to create objects. But a class can use the instance methods of a Module. In this way, without inheritance, several Classes can mixin the same Module, or several Modules can be mixed into a single class.
Example
The example code has two Modules, Math and Stringfy, and mixes them into BigInteger, a class made by inheriting from the Number class, to add the modules' methods to the object.
The Math module has a method called add, which passes the sum of two numbers to BigInteger as the initial value.
# filename : Math.rb
module Math
def add(value_one, value_two)
BigInteger.new(value_one+value_two)
end
end
The Stringfy module has a method called stringfy, which returns a string depending on the value of the object variable @value.
#filename : Stringfy.rb
module Stringfy
def stringfy
if @value == 1
"One"
elsif @value == 2
"Two"
elsif @value == 3
"Three"
end
end
end
The Number class has a method called inteValue, which returns the @value object.
The BigInteger class is made by inheriting from the Number class above; Stringfy is mixed into this class and it is extended with the Math methods.
#filename : BigInteger.rb
require 'Stringfy'
require 'Math'
require 'Number'
class BigInteger < Number
include Stringfy
extend Math
def initialize(value)
@value = value
end
end
Let's test it. The code below simply uses BigInteger, passes the value 10 to the constructor to create an object, and prints the value of the @value object variable with intValue, which Number had.