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.

About these ads

3 Comments to “Baking module methods into classes with alias_method”

  1. That’s very interesting. Out of curiosity, if the method you aliased changes, does the local copy change? I could see it going either way.

    • No the local copy does not change. A method alias appears to be an actual deep copy of the method, with the copy stored on the receiver.

  2. Thanks, this was really helpful to me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: