Ruby mixins, modules, require and include
Archive - Originally posted on "The Horse's Mouth" - 2008-11-16 15:38:58 - Graham EllisA Ruby "mixin" is a way of adding extra code from a module into a class - thus giving the programmer the ability to share code between a number of classes in a way that's in addition to inheritance. So - in effect - it gives multiple inheritance.
In some ways, you can compare a mixin to a (Java) interfaces which defines extra methods that you MUST have in a Java class in order for it to complete (implement) an interface. However, a Java interface is all to do with meeting the rules of the extra methods that must be provided and doesn't bring in any code at all, whereas in Ruby there are no such rules to be enforced (Ruby assumes you know what you are doing) and the mixin is all about bringing in the extra code.
We've got an example of a module for use in a mixin at tcalc.rb and a file that contains a class that uses it, together with a test harness here.
I have also written an example today that:
• loads a module via require
• then imports its namespace via include
which are the same basic principles as used in the mixin ... and I'm going to paste the source code below. Remember that require and include do different things in Ruby to they do in Perl ... in Ruby, require is used to load in a file (which probably contains a module) and include then brings its namespace into the current namespace.
Example: here's the file taxcalc.rb
module Taxcalc
VAT_RATE = 17.5
def net(gross)
net = gross / (100.0 + VAT_RATE) * 100.0
return net
end
def tax(gross)
tax = gross - net(gross)
end
end
And here's a sample program that uses it
# Drag in the file ...
require "taxcalc"
# And merge in its namespace
include Taxcalc
amount = 70.50
# because of the include, no need to say Taxcalc::net, etc
shopkeeper = net(amount)
vatman = tax(amount)
print "#{vatman} to the taxman\n"
print "#{shopkeeper} to the supplier\n"
print "Tax rate is #{VAT_RATE}\n"
See also here for a further example of modules, mixing and comparators in Ruby.
Code example written to illustrate our Ruby Training Courses