rubyreflectionalias-method

Is there an elegant way to test if one instance method is an alias for another?


In a unit test I need to test whether alias methods defined by alias_method have been properly defined. I could simply use the same tests on the aliases used for their originals, but I'm wondering whether there's a more definitive or efficient solution. For instance, is there a way to 1) dereference a method alias and return its original's name, 2) get and compare some kind of underlying method identifier or address, or 3) get and compare method definitions? For example:

class MyClass
  def foo
    # do something
  end

  alias_method :bar, :foo
end

describe MyClass do
  it "method bar should be an alias for method foo" do
    m = MyClass.new
    # ??? identity(m.bar).should == identity(m.foo) ???
  end
end

Suggestions?


Solution

  • According to the documentation for Method,

    Two method objects are equal if they are bound to the same object and contain the same body.

    Calling Object#method and comparing the Method objects that it returns will verify that the methods are equivalent:

    m.method(:bar) == m.method(:foo)