代码之家  ›  专栏  ›  技术社区  ›  Bryan Oakley

在ruby中,我如何知道哪个模块被定义为“load”或“require”的结果?

  •  3
  • Bryan Oakley  · 技术社区  · 17 年前

    在ruby中,如果我确实“需要foo”,是否有一种方法可以随后确定foo.rb中定义的一个或多个模块的名称?

    # foo.rb
    module MyModule
        def self.summary
            "this does something useful"
        end
        ...
    end
    

    在另一个脚本中,在我执行“requirefoo”之后,如何确定我现在有一个名为MyModule的模块?

    file = someComputedFileName()
    require file
    puts "summary of #{file}: #{???::summary}
    

    虽然我可以强迫自己使模块名和文件名相同,但我还是不愿意。我希望在制作短文件名方面有更多的自由,但模块名更具表现力。然而,我向自己保证,每个文件只定义一个模块(想想:插件)。

    2 回复  |  直到 17 年前
        1
  •  4
  •   Matt Ephraim    17 年前

    all_constants = Object.constants
    require 'foo'
    
    foo_constants = Object.constants - all_constants
    

    foo_常量应该只提供foo.rb定义的模块、类或其他常量。

        2
  •  3
  •   Jordan Liggitt    17 年前

    一种方法是使用 ObjectSpace

    require "set"
    old_modules = SortedSet.new
    ObjectSpace.each_object(Module) {|m| old_modules.add(m) }
    
    file = someComputedFileName()
    require file
    
    new_modules = SortedSet.new
    ObjectSpace.each_object(Module) {|m| new_modules.add(m) unless old_modules.include?(m) }
    
    puts "summary of #{file}: #{new_modules.to_a.map{|m|m.summary}.join(',')}"
    

    这样还可以在文件中定义多个模块。

    推荐文章