【问题标题】:Load a Ruby file from within the context of a Module?从模块的上下文中加载 Ruby 文件?
【发布时间】:2013-07-25 21:55:57
【问题描述】:

这是bar.rb

module Bar
end

现在,在 foo.rb 中,我想将其包含为 Foo 的子模块。我试过这个

module Foo
    load './bar.rb'
end

但这只是加载 bar.rb ,就好像它在全局命名空间中一样。使用上面的代码:

::Bar # => Bar
Foo::Bar # => NameError: uninitialized constant Foo::Bar

我正在寻找一种从模块上下文中加载文件的方法,以便切换上述结果——Foo::Bar 已定义但::Bar 未定义。基本上,它的结果类似于如果代码是这样的:

module Foo
    module Bar
    end
end

::Bar # => NameError: uninitialized constant Bar
Foo::Bar # => Foo::Bar

这可能吗?我正在使用 Ruby 1.9.3

【问题讨论】:

    标签: ruby module


    【解决方案1】:

    想通了,答案是使用eval

    module Foo
        eval IO.read('./bar.rb'), binding
    end
    
    ::Bar # => NameError: uninitialized constant Bar
    Foo::Bar # => Foo::Bar
    

    只需将文件作为字符串加载,并使用本地绑定进行评估。

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      相关资源
      最近更新 更多