我在Shopify 中使用了一个名为Script Editor的插件,但它给出了一个错误:undefined method 'end_with?' for nil
.
我的 Ruby 语法不太好,如果来自客户的电子邮件为空或不存在,请寻求有关如何退出命令的帮助:if customer && customer.email.end_with?("@mycompany.com")
这是Ruby 中的代码:
Input.cart.line_items.each do |line_item|
next if line_item.variant.product.gift_card?
discount = 1
customer = Input.cart.customer
if customer && customer.email.end_with?("@mycompany.com") //<< needs a better condition
message = "Lorem Ipsum"
discount = 0.2
end
next unless discount < 1
line_item.change_line_price(
line_item.line_price * discount,
message: message,
)
end
Output.cart = Input.cart
您可以使用 ruby 的安全导航运算符“&.”。
Input.cart.line_items.each do |line_item|
next if line_item.variant.product.gift_card?
discount = 1
customer = Input.cart.customer
if customer&.email&.end_with?("@mycompany.com")
message = "Lorem Ipsum"
discount = 0.2
end
next unless discount < 1
line_item.change_line_price(
line_item.line_price * discount,
message: message,
)
end
Output.cart = Input.cart
来自文档:
&.
,称为“安全导航操作符”,允许在接收器为零时跳过方法调用。如果调用被跳过,它返回 nil 并且不评估方法的参数。
参考:https : //ruby-doc.org/core-2.6/doc/syntax/calling_methods_rdoc.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句