【问题标题】:Can a ruby class statically keep track of subclasses?ruby 类可以静态跟踪子类吗?
【发布时间】:2011-10-15 00:18:04
【问题描述】:

我的目标是这样的:

class MyBeautifulRubyClass
  #some code goes here
end

puts MyBeautifulRubyClass.subclasses #returns 0

class SlightlyUglierClass < MyBeautifulRubyClass
end

puts MyBeautifulRubyClass.subclasses #returns 1

最好是地狱

puts MyBeautifulRubyClass.getSubclasses #returns [SlightlyUglierClass] in class object form

我确信这是可能的,只是不确定如何!

【问题讨论】:

  • 啊,我以为你的意思是笼统的。

标签: ruby


【解决方案1】:

这是一种低效的方法:

Look up all descendants of a class in Ruby

有效的方法是使用inherited 钩子:

class Foo
  def self.descendants
    @descendants ||= []
  end

  def self.inherited(descendant)
    descendants << descendant
  end
end

class Bar < Foo; end
class Zip < Foo; end

Foo.descendants #=> [Bar, Zip]

如果需要了解后代的后代,可以递归获取:

class Foo
  def self.all_descendants
    descendants.inject([]) do |all, descendant|
      (all << descendant) + descendant.all_descendants
    end
  end
end

class Blah < Bar; end

Foo.descendants     #=> [Bar, Zip]
Foo.all_descendants #=> [Bar, Blah, Zip]

【讨论】:

  • 这也与how Rails does it 非常相似。
  • 我可以打电话给 Bar.descendants 吗?要做到这一点需要什么?
  • @Volte 创建一个名为 DescendantsTracking 的模块,它具有继承的方法(作为常规方法,而不是单例方法),然后用它“扩展”Foo 和 Bar。
【解决方案2】:

不确定您是否可以在不去 ObjectSpace 的情况下做到这一点,比如 http://snippets.dzone.com/posts/show/2992,但这可能已经改变——只有一个解决方案。

【讨论】:

    猜你喜欢
    • 2011-06-09
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多