如何检查模块

时间:2016-03-31 19:10:13

标签: ruby

如何找出模块中定义的构造(方法,常量等)?

让我们说std::result_of<void (*(double))(double&)>,我希望看到所有在观察者中定义的内容。&#39;。我怎么能?

4 个答案:

答案 0 :(得分:2)

简短回答:你不能,不能绝对肯定。

长篇回答:这是Ruby如何成为一种非常动态的语言的产物,并且对require语句可能做的事情几乎没有约束。库可以创建任意数量的模块和类,并且不需要将它们整齐地组合在一起。

即使您在需要之前完成了对所有已定义的类和方法的快照的麻烦,然后在找到已添加的内容后又发现另一个快照,但无法保证您已全部捕获它们。在require语句完成后,可能会加载或定义某些类。

找出答案的最佳方法是阅读来源。在那里,您将看到可以定义的所有不同模块和类,即使它们不是由您的代码触发的。

methods这样的反射工具在某种程度上有所帮助,但它也具有很大的误导性。方法可以在以后定义,您可能需要更彻底地运用代码才能显示它们。

答案 1 :(得分:1)

如果你使用撬,只需做ls ModuleName

ls显示某个模块或类或实例的所有可用方法和实例变量。关于撬的更多信息:http://pryrepl.org/

或者你可以做到

ModuleName.instance_methods获取instance_methods

ModuleName.instance_variables获取instance_variables

作为另一个回答状态,几乎不可能(仍然可以用一种脆弱的方式)通过任意require

全面了解您的需求

imo,这种实现本身很脆弱且容易出错,除非它是你自己的模块并且你完全控制了API。但仍然不是一个好主意。

答案 2 :(得分:0)

您希望从要检查的模块外部执行Observer方法。以下是您可能会做的一个示例。

module Observer
  def self.show_all(mod)
    puts "owner of methods = #{mod.methods(false)}"
    puts "owner of instance methods = #{mod.instance_methods(false)}"
    puts "instance variables = #{mod.instance_variables}"
    puts "ancestors = #{mod.ancestors}"
    puts "included modules = #{mod.included_modules}"
  end
end

module A
  module B
    include Comparable
    @a = 1
    def self.b; end
    def c; end
    module C
    end
  end
end

Observer.show_all(A::B)
  # owner of methods = [:b]
  # owner of instance methods = [:c]
  # instance variables = [:@a]
  # ancestors = [A::B, Comparable]
  # included modules = [Comparable]

class D; end
class E<D; end
class F<E
  include Comparable
  @a = 1
  def self.e; end
  def f; end
end

Observer.show_all(F)
  # owner of methods = [:e]
  # owner of instance methods = [:f]
  # instance variables = [:@a]
  # ancestors = [F, Comparable, E, D, Object, Kernel, BasicObject]
  # included modules = [Comparable, Kernel]

答案 3 :(得分:0)

如果我不明白这个问题。

你可以这样做,阅读Module的属性。

示例:

第1版:

require "nokogiri"
p Nokogiri.methods # It will print for you all methods in that Module,
                   # also available methods from ruby.

第二版

x = require "nokogiri"
p x.methods #available methods there private, public, protected methods and etc...
p x.private_methods # prints bunch of private methods, [:Nokogiri] 
相关问题