by simon baird

Wednesday, July 07, 2010

Ruby: Module extend and include basics

For some reason or another I had never figured out why this kind of thing does't work as I expected it to:
module MyStuff
  def self.static_foo  # <--- does not work!
    puts "static foo"
  end
end

class MyClass
  include MyStuff
end

MyClass.static_foo #!> undefined method `static_foo' for MyClass:Class (NoMethodError)
I'd google around for the solution but never quite hit on it.

Long story short, I have finally figured it out and thought I would make this blog post about it. Please see the following example:
 1 
 2 module StaticStuff
 3   def static_foo
 4     puts "static foo"
 5   end
 6 end
 7 
 8 module InstanceStuff
 9   def foo
10     puts "foo"
11   end
12 end
13 
14 class MyClass
15   include InstanceStuff
16   extend StaticStuff
17 end
18 
19 MyClass.static_foo
20 MyClass.new.foo
21 

For more advanced techniques, see this interesting article by Yehuda about how rails uses three or four stones to kill this one bird. :)

No comments: