你如何递归地找到一个模块中的所有模块和类? [英] How do you find all modules and classes within a module, recursively?

查看:42
本文介绍了你如何递归地找到一个模块中的所有模块和类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有:

module A
  class B
  end
end

您可以通过 A.constants 找到 B 和类似的类.但是,在 Ruby 1.9.3 中,如果 B 位于另一个模块中,则无法获得 B.在 Ruby 1.8.7 中你可以.

You can find B and similar classes via A.constants. However, in Ruby 1.9.3, you cannot get B if it is within another module. In Ruby 1.8.7 you can.

module A
  module Aa
    class B
    end
  end
end

如何从A的第一级得到B?我想要的输出是一个常量数组,其中包括像 B 这样的所有类,但在模块 A 中的任何地方.

How do you get B from the first level of A? What I would like as output is an array of constants, which include all classes like B, but anywhere within the module A.

推荐答案

class Module
  def all_the_modules
    [self] + constants.map {|const| const_get(const) }
      .select {|const| const.is_a? Module }
      .flat_map {|const| const.all_the_modules }
  end
end

A.all_the_modules
# => [A, A::Aa, A::Aa::B]

如果您确实有循环命名空间,即此代码将中断A::Aa::B.const_set(:A, A).

This code will break if you do have circular namespaces, aka A::Aa::B.const_set(:A, A).

这篇关于你如何递归地找到一个模块中的所有模块和类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆