【发布时间】: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