I am working in Shopify with a plugin called Script Editor and it is giving an error: undefined method 'end_with?' for nil
.
My syntax for Ruby is not so great and wanted to ask for help on how to exit the command if an empty or non existent email from customer on this line: if customer && customer.email.end_with?("@mycompany.com")
Here's the code in 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
CodePudding user response:
You can use ruby's safe navigation operator `&.'.
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
From doc's:
&.
, called “safe navigation operator”, allows to skip method call when receiver is nil. It returns nil and doesn't evaluate method's arguments if the call is skipped.
Reference: https://ruby-doc.org/core-2.6/doc/syntax/calling_methods_rdoc.html