ruby - 我能否编写仅在我的脚本运行时执行但在需要时不执行的 Ruby 代码?

标签 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
# ------------------------------------------------------------------------------------------

我希望能够对其进行单元测试,这就是为什么我不希望类外的代码运行,除非我直接执行脚本,即 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/

相关文章:

ruby - 替代 eval()

ruby - 使用哈希默认值时出现奇怪的意外行为(消失/更改值),例如哈希.new([])

ruby db结果集到散列中的数组

ruby - 访问 Ruby 对象中的字符串

ruby-on-rails - 我得到 "Missing these required gems",但安装了 gem

ruby - 如何使用 Ruby 中的 Mechanize 提交表单?

ruby - 如何格式化 BigDecimal 以仅显示所需数量的十进制数字?

arrays - 根据值从数组中选择索引

ruby - Rake 使用 neo4j :install[community-2. 1.5 中止]

html - link_to_unless_current 将类分配给禁用的(当前)链接