Posts tagged ‘mixins’

November 4, 2010

Baking module methods into classes with alias_method

Here is a trick to bake a module’s methods directly into a class:

module M
  def hello
    puts "hello defined in M"
  end
end

class C
  include M
  alias_method :hello, :hello
end

The magic is in the line alias_method :hello, :hello. This code creates an alias for the hello method defined in M directly on the C class itself.

C.instance_method(:hello).owner #=> C

The hello method is now safe from being accidentally overridden by other modules included subsequently:

module J
  def hello
    puts "hello defined in J"
  end
end

class C
  include J
end

C.new.hello #=> "hello defined in M"

Note that this trick only works in Ruby 1.9 as `alias_method :meth, :meth` in Ruby 1.8 appears to be a no-op.

Follow

Get every new post delivered to your Inbox.