动态调用动态语言,第 2 部分: 在运行时寻找、执行和修改脚本
2009-11-19 00:00:00 来源:WEB开发网注意,JavaScript 代码不能像 Groovy 脚本那样使用 Java scriptExit.withMessage() 方法在一个语句中设置不合格消息并退出脚本。这是因为 Rhino JavaScript 解释器并不把抛出的 Java 异常在 ScriptException 堆栈跟踪中作为嵌入的 “错误原因” 向上传递。因此,在堆栈跟踪中更难找到 Java 代码抛出的脚本异常消息。所以 清单 5 中的 JavaScript 代码需要单独设置结果消息,然后再调用 scriptExit.noMessage() 来产生异常,从而终止脚本处理。
第三个抵押产品脚本是用 Ruby 编写的,见清单 6。这种抵押产品要求贷款人具有良好的信用记录,他们可以支付百分之二十的首付款。
清单 6. Ruby 抵押脚本# This Ruby script defines the "Ruby Mortgage" product.
# It is intended for premium borrowers with its low interest rate
# and 20% down payment requirement.
# Our product name
$result.product_name = 'Ruby Mortgage'
# Borrowers with credit unworthiness do not qualify.
if $borrower.credit_score < 700
$scriptExit.with_message "Credit score of #{$borrower.credit_score}" +
" is lower than 700 minimum"
end
$scriptExit.with_message 'No bankruptcies allowed' if $borrower.hasDeclaredBankruptcy
# Check other negatives
down_payment_percent = $loan.down_payment / $property.sales_price * 100
if down_payment_percent < 20
$scriptExit.with_message 'Down payment must be at least 20% of sale price.'
end
# Borrower qualifies. Determine interest rate of loan
$result.message = "Qualified!"
$result.qualified = true
# Give the best interest rate to the best credit risks.
if $borrower.credit_score > 750 || down_payment_percent > 25
$result.interestRate = 0.06
elsif $borrower.credit_score > 700 && $borrower.totalAssets > 100000
$result.interestRate = 0.062
else
$result.interestRate = 0.065
end
在 JRuby 1.0 中不要忘记 $ 符号
更多精彩
赞助商链接