Can I write Ruby code that is executed only when my script is run, but not when it is required?
我想写一个这样的Ruby脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 # ------------------------------------------------------------------------------------------ |
我希望能够对它进行单元测试,这就是为什么我不希望类外的代码运行,除非我直接执行脚本,即
我知道我可以简单地将
这通常是用
1 2 3 | if __FILE__ == $0 Foo.run end |
但我更喜欢
1 2 3 | if File.identical?(__FILE__, $0) Foo.run end |
因为像ruby prof这样的程序即使在使用