jeudi 1 décembre 2016

How do I find a method's nesting in Ruby?

In Ruby, constant lookup is affected by nesting and methods retain their nesting.

For example, if I have these modules:

module A
  X = 1
end

module B
  X = 2
end

module Foo
end

I can define a method Foo.a that has a nesting of [A, Foo]:

module Foo
  module ::A
    Module.nesting #=> [A, Foo]
    def Foo.a
      X
    end
  end
end

Foo.a #=> 1

And a method Foo.b that has a nesting of [Foo, B]:

module B
  module ::Foo
    Module.nesting #=> [Foo, B]
    def Foo.b
      X
    end
  end
end

Foo.b #=> 2

The difference becomes apparent if I define Foo::X:

Foo::X = 3

Foo.a #=> 1  <- still resolves to A::X
Foo.b #=> 3  <- now resolves to Foo::X

But how do I determine the nesting of a given method?





Aucun commentaire:

Enregistrer un commentaire