开发者

ruby: How can I get all the Class and/or Module objects that are a child of a Module?

Supposing I have the following:

module A
  class B
    # ...
  end

  # ...
end

And suppose I have开发者_开发问答 several different files like this, with different values of B, but all in the same module (A). From a program that require's a file that then require's each of these files, is there a way with introspection/reflection (are these different things? I'm hazy on the distinction, if so) to determine (and get objects for) each class within the module?

I've tried this, which gets me sort of close:

A.constants # => ["B"]

But I'd prefer to get back [A::B], rather than a string, so that I can then call something like singleton_methods on it, which would be useful to my program, which is attempting to map data into calls into the various subclasses' methods.

Is there some way to do this? I've been digging for answers, and found a few related things, like this or this, but nothing that's quite spot on.


Hah! Wouldn't you know it? Just after writing this, I discovered an answer that seems to work for me:

A.constants.collect{|k| A.const_get(k)}.select {|k| k.is_a?(Class)} # => [A::B]

Sweet, that was easy, once I put the right pieces together. :)


thats my final solution based on lindes answer:

    def all_classes_in_module_except_base(module_class)
      Dir["#{Rails.root}/app/domains/#{module_class.to_s.underscore}s/*.rb"].each { |file| load file }
      module_class.constants.collect { |k| module_class.const_get(k) }.select { |k|
        k.is_a?(Class) && k.name.demodulize != "Base"
      }
    end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜