【问题标题】:Can I write Ruby code that is executed only when my script is run, but not when it is required?我可以编写仅在我的脚本运行时执行的 Ruby 代码,而不是在需要时执行吗?
【发布时间】:2011-09-21 00:08:42
【问题描述】:

我想写一个像这样的 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 中做到这一点。

【问题讨论】:

  • Run a Ruby library from the command-line 的可能重复项 - 但需要认真的谷歌搜索才能找到它!我很惊讶这个问题没有被更多地问到。
  • 安德鲁:这里也一样。我希望已经在 Stack Overflow 上找到答案!再次感谢您的帮助。

标签: ruby


【解决方案1】:

这通常是用

完成的
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__ 是当前源文件的名称。

【讨论】:

  • 非常直接。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多