Is there a way of dividing the money object, or converting it to a Number to do the same?
I should precurse this with a note that I'm not familiar with Ruby, so I may be missing something obvious.
I'm trying to calculate the percentage a line price is of the total of the cart.
e.g line_item.line_price / cart.subtotal_price
But as per the scripts documentation the Money object doesn't have a divide method.
The scenario is that we want to offer a 20% discount, that maxes out at 500 dollars, after which the discount is a maximum of $100.
If there is a different approach to achieving that result other then shopify scripts, that would also be of great help.
Therefore out of a maximum of $100 the discounted price would be:
Here is what the ideal scenario is if I could divide the money object:
if (Input.cart.discount_code) if (Input.cart.subtotal_price > (Money.new(cents: 100) * 500)) cart_total = Input.cart.subtotal_price Input.cart.line_items.each do |line_item| line_price = line_item.line_price percentage_of_total = line_price / cart_total discount_of_line = percentage_of_total * 100 line_item.change_line_price(line_price - discount_of_line, message: "Success") end else Input.cart.line_items.each do |line_item| line_price = line_item.line_price line_item.change_line_price(line_price * 0.8, message: "Success!") end end end Output.cart = Input.cart
Any help would be greatly appreciated :)
Zoran - you can't divide money values, but you can multiply them by a fraction, eg:
a = Money.new(cents: 100) b = a * (1.0 / 2.0)
As a fallback, you can also extract the number of cents from a Money object, perform calculations on that, and turn it back into a Money object:
a = Money.new(cents: 100) b = Money.new(cents: (a.cents / 2))