简体   繁体   English

如何在Ruby中没有在Object上定义其常量的情况下要求一个文件?

[英]How do I require a file without defining it's constants on Object in Ruby?

I would like to require a file in Ruby without defining that file's constants on Object. 我想在Ruby中要求一个文件,而不在Object上定义该文件的常量。 Instead I would like to include them only in a module in the requiring file. 相反,我只想将它们包括在需求文件中的模块中。 For instance if I have a file foo.rb that looks like this: 例如,如果我有一个如下所示的文件foo.rb:

module Foo
  def self.hello_world
    puts 'Hello, World.'
  end
end

A representation of the result I hope to achieve looks something like this: 我希望达到的结果的表示形式如下所示:

module Bar
  require_relative './foo.rb'
end

Foo.hello_world
# NameError: uninitialized constant Foo

Bar::Foo.hello_world
# Hello, World.

It seems like the way things are required in Ruby, anything defined at the top level of another file will be defined as a constant on Object and thus globally available. 好像在Ruby中需要的方式一样,在另一个文件的顶层定义的任何内容都将被定义为Object上的常量,因此是全局可用的。 I'm having a problem because I need something from a file that conflicts with a constant in the global namespace. 我遇到了问题,因为我需要文件中与全局命名空间中的常量冲突的内容。

I recognize that this problem may be fundamental to Ruby, but is it possible there's some metaprogramming technique to overcome this issue? 我认识到这个问题对于Ruby可能是根本的,但是是否有某种元编程技术可以克服这个问题呢?

It looks like the following snippet works for what I'm trying to do: 看来以下片段适用于我要执行的操作:

module Bar
  class_eval File.open('./foo.rb').read
end

It may be that I'm still missing something though. 可能是我仍然缺少一些东西。

If you don't need to access the ancestor, what you're looking for is extend 如果您不需要访问祖先,那么您正在寻找的是extend

module Foo
  def hello_world
    puts 'Hello, World.'
  end
end

module Bar
  extend Foo 
end


Bar.hello_world

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM