2010-12-15 76 views
0

我在兩個不同的環境(Windows XP和Linux)中運行Buildr,因此我在不同位置安裝了本地Java和Scala。我有以下做法來檢查環境變量設置:如何優雅地放棄Buildr?

require 'buildr/scala' 
# Can I put these checks on a function ? How ? 
ENV['JAVA_HOME'] ||= Buildr.settings.user['java_home'] 
if ENV['JAVA_HOME'].nil? then 
    puts "Required environment variable JAVA_HOME was not set. Value can also be set in personal settings." 
    Process.exit 1 
end 
puts 'JAVA_HOME = ' + ENV['JAVA_HOME'] 

ENV['SCALA_HOME'] ||= Buildr.settings.user['scala_home'] 
if ENV['SCALA_HOME'].nil? then 
    puts "Required environment variable SCALA_HOME was not set. Value can also be set in personal settings." 
    Process.exit 1 
end 
puts 'SCALA_HOME = ' + ENV['SCALA_HOME'] 

puts 'Scala version: ' + Scala.version 

define "HelloWorld" do 
    puts 'Hello World !' 
end 

但是我怎麼退出Buildr,使之與這種消息的退出:

Buildr aborted! 
RuntimeError : Scala compiler crashed: 
#<NullPointerException: unknown exception> 
(See full trace by running task with --trace) 

我應該拋出一個異常(如果是的話,如何在Ruby中做到這一點)?

回答

3

嘗試fail

if ENV['SCALA_HOME'].nil? then 
    fail "Required environment variable SCALA_HOME was not set. Value can also be set in personal settings." 
end 

fail拋出紅寶石異常。您也可能會看到它叫raise;他們是相等的。如果不指定類型,則異常類型將爲RuntimeError,如在「編譯器崩潰」示例中一樣。

獎金回答:如果您想將這些支票放入一個函數中(如您對第一個函數的建議),您可以在項目的頂層創建一個名爲tasks的目錄,然後將一個文件放在.rake在它的擴展。在那裏定義你的功能。 Buildr將在評估您的構建文件之前加載所有這些文件。

例如,你可以有一個名爲tasks/helpers.rake這些內容的文件:

def initialize_environment 
    ENV['JAVA_HOME'] ||= Buildr.settings.user['java_home'] 
    unless ENV['JAVA_HOME'] 
    fail "Required environment variable JAVA_HOME was not set. Value can also be set in personal settings." 
    end 
    puts "JAVA_HOME = #{ENV['JAVA_HOME']}" 
    # etc. 
end 

(注:我改變了一些其他細節 - unless,串插 - 更紅寶石idomatic方式你有很細,太,如果你喜歡的)

然後在你的構建文件的頂部,你可以有這樣的:

require 'buildr/scala' 
initialize_environment 
# etc. 
+0

回答我的所有問題並向我介紹了其他有用的東西。我除了除非關鍵字(我更喜歡'如果不是'),所有這些都被使用了。謝謝 ! – user272735 2010-12-16 19:38:20