Frage
Ich betreiben Buildr in zwei verschiedenen Umgebungen (Windows XP und Linux) und deshalb habe ich lokale Java und Scala Installationen an verschiedenen Standorten. Ich habe die folgende Praxis zu überprüfen, dass die Umgebungsvariablen gesetzt sind:
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
Aber wie beende ich Buildr, so dass es mit dieser Art von Nachricht beendet:
Buildr aborted!
RuntimeError : Scala compiler crashed:
#<NullPointerException: unknown exception>
(See full trace by running task with --trace)
Soll ich eine Ausnahme aus (wenn ja, wie das in Ruby tun)?
Lösung
Try 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
throws an exception in ruby. You might also see it called raise
; they're equivalent. If you don't specify a type, the exception type will be RuntimeError
as in your "compiler crashed" example.
Bonus answer: If you want to put these checks in a function (as your comment on the first one suggests), you can create a directory called tasks
at the top level of your project, then put a file with a .rake
extension in it. Define your functions there. Buildr will load all such files before evaluating your buildfile.
For example, you could have a file named tasks/helpers.rake
with these contents:
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
(Note: I changed a couple of other details — unless
, string interpolation — to be more ruby-idomatic. The way you had it was fine, too, if you prefer that.)
Then at the top of your buildfile you could have this:
require 'buildr/scala'
initialize_environment
# etc.