Ruby: Defining Instance and Class methods in Modules 1

Posted by science on August 05, 2007

Caravagio Narcissus: reflection of self

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"
Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. science Fri, 28 Dec 2007 23:46:19 EST

    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/

Comments