获取常量的所有者
Getting the owner of a constant
使用(n inherited)方法,定义它的receiver/class可以通过以下方式实现:
class A
def foo; end
end
class B < A
end
B.instance_method(:foo).owner # => A
有了一个(n inherited) 常量,没有对应的instance_method
或method
方法,所以它不是直截了当的。是否可以在定义的地方实现class?
class A
Foo = true
end
class B < A
end
B.some_way_to_extract_the_owner_of_constant(:Foo) # => A
喜欢,下面的代码:
class A
Foo = true
end
class B < A
end
B.ancestors.find { |klass| klass.const_defined? :Foo, false }
# => A
类似于@Arup 的回答,但我使用了 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
使用(n inherited)方法,定义它的receiver/class可以通过以下方式实现:
class A
def foo; end
end
class B < A
end
B.instance_method(:foo).owner # => A
有了一个(n inherited) 常量,没有对应的instance_method
或method
方法,所以它不是直截了当的。是否可以在定义的地方实现class?
class A
Foo = true
end
class B < A
end
B.some_way_to_extract_the_owner_of_constant(:Foo) # => A
喜欢,下面的代码:
class A
Foo = true
end
class B < A
end
B.ancestors.find { |klass| klass.const_defined? :Foo, false }
# => A
类似于@Arup 的回答,但我使用了 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