Question

I run Buildr in two different environments (Windows XP and Linux) and therefore I have local Java and Scala installations in different locations. I have the following practice to check that the environment variables are set:

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

But how do I exit Buildr so that it exits with this kind of message:

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

Should I throw an exception (if yes, how to do that in Ruby) ?

Was it helpful?

Solution

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top