我在两个不同的环境(Windows XP和Linux)中运行Buildr,因此我在不同的位置安装了本地Java和Scala。我有以下练习来检查是否设置了环境变量:
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中执行此操作)?
答案 0 :(得分: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
在ruby中抛出异常。你可能也会看到它叫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
,字符串插值 - 更加像红宝石一样。如果您愿意的话,您的方式也很好。)
然后在构建文件的顶部你可以拥有:
require 'buildr/scala'
initialize_environment
# etc.