Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the owner of a constant

With a(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 a(n inherited) constant, there is no counterpart to instance_method or method method, so it is not straightforward. Is it possible to achieve 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
like image 938
sawa Avatar asked Mar 14 '23 05:03

sawa


1 Answers

Like, the below code:

class A
  Foo = true
end

class B < A
end

B.ancestors.find { |klass| klass.const_defined? :Foo, false }
# => A
like image 58
Arup Rakshit Avatar answered Mar 24 '23 05:03

Arup Rakshit