我可以轻松地提升Ruby中的类层次结构:
String.ancestors # [String, Enumerable, Comparable, Object, Kernel]
Enumerable.ancestors # [Enumerable]
Comparable.ancestors # [Comparable]
Object.ancestors # [Object, Kernel]
Kernel.ancestors # [Kernel]
Run Code Online (Sandbox Code Playgroud)
有没有办法下降层次结构?我想这样做
Animal.descendants # [Dog, Cat, Human, ...]
Dog.descendants # [Labrador, GreatDane, Airedale, ...]
Enumerable.descendants # [String, Array, ...]
Run Code Online (Sandbox Code Playgroud)
但似乎没有一种descendants方法.
(出现这个问题是因为我想找到Rails应用程序中的所有模型,这些模型来自基类并列出它们;我有一个控制器可以使用任何这样的模型,我希望能够添加新模型无需修改控制器.)
我有一个用一堆类方法定义的实用程序类.在Rails控制台中,当我使用Object.const_defined?它搜索类时返回false.但在调用其中一个类方法或创建该类的实例后,Object.const_defined?返回true.这是因为某种延迟加载实例化的事情吗?有没有其他方法可以检查是否存在将返回true的类,即使我还没有实例化任何东西?