How to test method alias ruby

前端 未结 4 1882
夕颜
夕颜 2021-01-13 14:50

How to test if if method has an alias?

Let\'s say we have

Class Test
  class << self
    def a;end
    alias :b :a
  end
end

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-13 15:27

    oldergod's answer works in most scenarios:

    Test.method(:b) == Test.method(:a)
    

    Unfortunately it doesn't work in Ruby 2.3+ when the two methods have different owners (e.g. when the method is defined in a module, and the alias is defined in a class that includes the module). This is because the behavior of Method#== changed in Ruby 2.3:

    If owners of methods are different, the behavior of super is different in the methods, so Method#== should not return true for the methods.

    If you find yourself in this situation, where you want to test that two methods are aliases of each other but they have different owners, you can use Method#original_name or Method#source_location instead:

    Test.method(:b).original_name == Test.method(:a).original_name
    Test.method(:b).source_location == Test.method(:a).source_location
    

提交回复
热议问题