加载一个Ruby代码文件
具有以下文件:加载一个Ruby代码文件,ruby,oop,Ruby,Oop,具有以下文件: # ./app.rb require_relative 'container' require_relative 'contained' # ./container.rb class Foo def initialize &block puts block.call end end # ./contained.rb Foo.new do "Hello, world!" end 我们可以从控制台测试并查看一切是否正常: $ ruby ./app.r
# ./app.rb
require_relative 'container'
require_relative 'contained'
# ./container.rb
class Foo
def initialize &block
puts block.call
end
end
# ./contained.rb
Foo.new do
"Hello, world!"
end
我们可以从控制台测试并查看一切是否正常:
$ ruby ./app.rb
Hello, world!
但是我想通过删除Foo.new do
和end
来简化contained.rb,通过修改app.rb只保留块的内容
在这次探索中,我得到了以下结果:
# ./app.rb
require_relative 'container'
require_relative 'contained'
Foo.new do
eval File.open('contained.rb').read
end
# ./container.rb
class Foo
def initialize &block
puts block.call
end
end
# ./contained.rb
"Hello, world!"
同样的结果是:
$ ruby ./app.rb
Hello, world!
然而,我对这段代码不是很自豪,主要是因为eval
方法。在这种情况下有没有最佳做法?你会怎么做?
感谢分享您的想法。您希望从单独的文件中读取的事实必须是您希望将其与主代码分开,并且您希望偶尔对其进行更改。这类东西属于所谓的配置。现在,将其作为YAML文件编写并使用YAML库读入Ruby是很常见的。我将在第一个示例中保留它。第二,除了使用eval外,还为代码引入了一些魔力,可能会让您或其他开发人员在几周/几个月/几年内挠头。是什么帮助您决定使用eval?我同意。这不值得努力。保留第一个示例中的代码更明智。谢谢你,@a-fader-darkly。谢谢你的回答,@sawa!我现在看得更清楚了。