我想寫一個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中做到這一點感興趣。
[從命令行運行Ruby庫]的可能的重複(http://stackoverflow.com/questions/487086/run-a-ruby-library-from-the-command-line) - 但它花了一些嚴重的谷歌搜索找到它!我很驚訝這個問題並不是經常被問到。 –
Andrew:這裏一樣。我希望能夠在Stack Overflow上找到答案!再次感謝您的幫助。 –