2011-06-23 32 views
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 
# ------------------------------------------------------------------------------------------ 

我希望能夠單元測試,這就是爲什麼我不希望外部類的代碼運行,除非我執行腳本直接,即ruby foo_it_up.rb

我知道我可以簡單地將Foo類放在另一個文件中,require 'foo'放在我的腳本中。事實上,這可能是一個更好的方法,以防萬一Foo的功能需要其他地方。所以我的問題比任何東西都更具學術性,但我仍然對知道如何在Ruby中做到這一點感興趣。

+1

[從命令行運行Ruby庫]的可能的重複(http://stackoverflow.com/questions/487086/run-a-ruby-library-from-the-command-line) - 但它花了一些嚴重的谷歌搜索找到它!我很驚訝這個問題並不是經常被問到。 –

+0

Andrew:這裏一樣。我希望能夠在Stack Overflow上找到答案!再次感謝您的幫助。 –

回答

20

這通常是

if __FILE__ == $0 
    Foo.run 
end 

這樣做,但我更喜歡

if File.identical?(__FILE__, $0) 
    Foo.run 
end 

因爲像紅寶石教授can make $0 not equal__FILE__程序即使您使用--replace-progname

$0是指程序的名稱($PROGRAM_NAME),而__FILE__是當前源文件的名稱。

+0

非常簡單。謝謝! –

相關問題