我想写一个像这样的 Ruby 脚本:
class Foo
# instance methods here
def self.run
foo = Foo.new
# do stuff here
end
end
# This code should only be executed when run as a script, but not when required into another file
unless required_in? # <-- not a real Kernel method
Foo.run
end
# ------------------------------------------------------------------------------------------
我希望能够对其进行单元测试,这就是为什么我不希望类外的代码运行,除非我直接执行脚本,即 ruby foo_it_up.rb
。
我知道我可以简单地将 Foo
类放在另一个文件中并在我的脚本中 require 'foo'
。事实上,这可能是一种更好的方法,以防万一 Foo
的功能在其他地方需要。所以我的问题比任何问题都更具学术性,但我仍然有兴趣知道如何在 Ruby 中做到这一点。
最佳答案
这通常是用
if __FILE__ == $0
Foo.run
end
但我更喜欢
if File.identical?(__FILE__, $0)
Foo.run
end
因为程序像 ruby-prof can make $0 not equal __FILE__
即使您使用 --replace-progname
。
$0
是指程序的名称($PROGRAM_NAME
),而__FILE__
是当前源文件的名称。
关于ruby - 我能否编写仅在我的脚本运行时执行但在需要时不执行的 Ruby 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6450846/