Getting Owner Permanent

Using the (n inherited) method, the receiver / class where it is defined can be achieved by doing:

class A
  def foo; end
end

class B < A
end

B.instance_method(:foo).owner # => A

With the help of the (n inherited) constant, there is no analog of the method instance_methodor method, therefore, it is not easy. Is it possible to reach the class where it is defined?

class A
  Foo = true
end

class B < A
end

B.some_way_to_extract_the_owner_of_constant(:Foo) # => A
+4
source share
2 answers

Like below code:

class A
  Foo = true
end

class B < A
end

B.ancestors.find { |klass| klass.const_defined? :Foo, false }
# => A
+5
source

Like @Arup answer, but I used Module # constants .

class Base
end

class A < Base
  Foo = true
end

class B < A
  Foo = false
end

class C < B
end

C.ancestors.find { |o| o.constants(false).include?(:Foo) }
  #=> B
+2
source

Source: https://habr.com/ru/post/1629754/


All Articles