I wish someone had shown me how to use Module methods correctly for creating “multiple inheritance” like features in Ruby. The “Pickaxe” book does a pretty good job (pub. Pragmatic Programmers) but all the info was scattered around a little. I thought I’d share a short piece of code which demonstrates easily how to introduce module methods into classes. You can install them either as class methods or instance methods. When referencing variables in these modules (such as “self”) after you install them into a Class, those references will refer to variables inside the Class, which is very handy. Ruby uses quite a bit of this internally, to implement iterators and other functions across multiple classes - in fact you can implement Classes and mix-in iteration if you support a few underlying functions that the iterator module needs to function.
module Classes
def class_def
puts 'class_def called'
end
end
module Instances
def instance_def
puts 'instance_def called'
end
end
class Foo
include Instances
extend Classes
end
Foo.class_def
# output is "class_def called"
f = Foo.new
f.instance_def
# output is "instance_def called"
Science recently found this article which may be of interest to readers of the Method. It goes into much more detail and includes some crucial concepts for real-world work, like how to create an initializer in your module when extending it into a class.. hint: “def extended(base)” Enjoy!
http://www.juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/