Ruby: Modules, Mixins, Fixins, and Rails - A Few Notes
(Page 2 of 4 )
If you are calling the modules from outside of Ruby, you should use the include statement instead of the require statement, like so:
include 'addition.rb'
You can store classes inside of modules if you wish:
module Mathstuff
class Adding
def Adding.add(operand_one, operand_two)
return operand_one + operand_two
end
end
end
And then to call the method (which resides in the class inside of the module) you can use the scope resolution operator(::):
module Mathstuff
class Adding
def Adding.add(operand_one, operand_two)
return operand_one + operand_two
end
end
end
puts “What is 10 + 10?”
puts “The answer is: “ + Mathstuff::Adding.add(10, 10).to_s
Here the result is:
What is 10 + 10?
The answer is: 20
Puttin' on the Mix
The best way to describe a mixin is to say that it is a class mixed with a module. One of the benefits of using a mixin is that it gives you the ability to inherit from several modules all at once.
Here is an example:
module Adding
def add(value_one, value_two)
return value_one + value_two
end
end
module Subtract
def subtract(value_one, value_two)
return value_one - value_two
end
end
class Mathmagician
include Adding
include Subtract
end
mathmagician = Mathmagician.new()
puts "The difference between my looks and your looks is: " + mathmagician.subtract(10,2).to_s
puts "Our combined looks are " + mathmagician.add(10,2).to_s
The result of this program is:
The difference between my looks and your looks is: 8
Our combined looks are 12
In the above example we create two modules and add them to the Mathmagician class, which inherits the adding and subtract methods, basically meaning that Mathmagician can now add or subtract, or both. If we had added a division module, we could have added it to the Mathmagician class, and then been able to divide by typing mathmagician.divide.
Next: Going off the Rails of the Crazy Train >>
More Ruby-on-Rails Articles
More By James Payne