我想提交带有可选选项的车道。例如车道:
lane :mylane do |options|
mailgun(
to: "#{options[:mailto]}"
....
)
end
如何为
:mailto
指定默认值?因此,如果我运行 fastlane mylane
,它会自动将 :mailto
设置为 [电子邮件受保护]。
但是如果我运行
fastlane mylane mailto:"[email protected]"
它将使用该值
正如用户Lyndsey Ferguson在这个答案的评论中指出的那样,以下是最简单的:
mail_addr = options.fetch(:mailto, '[email protected]')
其中
fetch
的第一个参数是要获取的选项,如果没有传入选项,第二个参数是默认值。
我只是想补充一点,这比其他建议要好得多:
options[:mailto] || '[email protected]'
处理布尔选项时。
Fastlane(或者也许是 Ruby)将
true
、false
、yes
和 no
解释为布尔值而不是字符串(也许还有其他值,尽管我尝试过 N
、n
、NO
,和 FALSE
并且它们被视为字符串),所以如果在你的车道实现中你有:
options[:my_option] || true
或
(options[:my_option] || 'true') == 'true'
你会得到意想不到的行为。
如果您根本没有传入
myOption
,则如您所料,这将默认为 true
。如果您传入 true
,这也会返回 true
。但如果你传入 false
这会变成 true
,你当然不希望这样。
使用
options.fetch(:myOption, true)
与上面提到的布尔标志配合使用效果很好,因此一般情况下使用似乎更好。
这是一个非常全面的示例,以防您想自己测试一下:
lane :my_lane do |options|
puts("You passed in #{options[:my_option]}")
my_option = options[:my_option] || true
if my_option
puts('Using options[:my_option], the result is true')
else
puts('Using options[:my_option] the result is false')
end
my_option_fetched = options.fetch(:my_option, true)
if my_option_fetched
puts('Using fetched, the result is true')
else
puts('Using fetched, the result is false')
end
end
输出:
fastlane my_lane my_option:true
你真的通过了
使用options[:my_option],结果为true
使用fetched,结果为true
fastlane my_lane my_option:false
你传错了
使用options[:my_option],结果为true
使用fetched,结果为false
fastlane my_lane my_option:no
你传错了
使用options[:my_option],结果为true
使用fetched,结果为false
注意,例如
FALSE
将默认为 true
,因为它没有被解释为布尔值,这对我来说似乎是合理的。
(快车道1.77.0,红宝石2.7.2)
编辑:值得注意的是,如果您传递空字符串而不是空字符串/null,您将无法从
fetch
方法中获得默认值。
我不确定是否有办法让 Fastlane 通过默认设置。处理非常简单:
https://github.com/fastlane/fastlane/blob/master/fastlane/lib/fastlane/command_line_handler.rb#L10
但是您可以在 Fastfile 中轻松执行此操作:
lane :mylane do |options|
mail_addr = options[:mailto] || "[email protected]"
mailgun(
to: "#{mail_addr}"
....
)
end