我是否可以编写仅在运行脚本时执行的Ruby代码,而不是在需要时执行的代码?

Jos*_*ver 8 ruby

我想写一个像这样的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
# ------------------------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

我希望能够对它进行单元测试,这就是为什么我不想让类外的代码运行,除非我直接执行脚本,即ruby foo_it_up.rb.

我知道我可以简单地将该Foo类放在另一个文件和require 'foo'我的脚本中.事实上,这可能是一种更好的方法,以防万一Foo其他地方需要功能.所以我的问题比任何事情更具学术性,但我仍然有兴趣知道如何在Ruby中做到这一点.

And*_*imm 20

这通常是用

if __FILE__ == $0
  Foo.run
end
Run Code Online (Sandbox Code Playgroud)

但是我更喜欢

if File.identical?(__FILE__, $0)
  Foo.run
end
Run Code Online (Sandbox Code Playgroud)

因为像ruby-prof这样的程序即使在使用时也会使$ 0不相等 .__FILE__--replace-progname

$0是指程序($PROGRAM_NAME)__FILE__的名称,而是当前源文件的名称.