Thursday, May 10, 2007

ruby module_function

Ruby 'module' allows us to define methods then turn these methods into instance methods of a class by using key word 'include'. In ruby world, peoples call this feature 'mixin'. e.g.

module Foo
   def hello
      puts 'hello'
   end
end
class Bar
include Foo
end
Bar.new.hello #=> hello

Sometime we need to call method defined in a module without including the module into a class. We can do it by

module Foo
  def self.world
     puts 'world'
  end
end
Foo.world #=> world

There is a question how do we turn method 'hello' so it can be used in both mixin style and standalone . The answer is using kernel method 'module_function'

module Foo
   module_function :hello
end
Foo.hello + ' ' + Foo.world # => hello world

No comments: