Class: SolidusPromotions::Calculators::Percent

Inherits:
Spree::Calculator
  • Object
show all
Includes:
PromotionCalculator
Defined in:
app/models/solidus_promotions/calculators/percent.rb

Overview

A calculator that applies a percentage-based discount.

This calculator computes the discount as a percentage of the item’s discountable amount, rounded to the appropriate currency precision.

Examples:

calculator = Percent.new(preferred_percent: 15)
# Line item with discountable_amount of $100
calculator.compute_item(line_item) # => 15.00 (15% of $100)

Instance Method Summary collapse

Methods included from PromotionCalculator

#description

Instance Method Details

#compute_item(object, _options = {}) ⇒ BigDecimal Also known as: compute_line_item, compute_shipment, compute_shipping_rate, compute_price

Computes the percentage-based discount for an item.

Calculates the discount by applying the preferred percentage to the item’s discountable amount, then rounds the result to the appropriate precision for the order’s currency.

Examples:

Computing a 20% discount on a $50 line item

calculator = Percent.new(preferred_percent: 20)
line_item.discountable_amount # => 50.00
calculator.compute_item(line_item) # => 10.00

Computing a 15% discount on a shipment

calculator = Percent.new(preferred_percent: 15)
shipment.discountable_amount # => 25.00
calculator.compute_item(shipment) # => 3.75

Computing a 15% discount on a price

calculator = Percent.new(preferred_percent: 15)
price.discountable_amount # => 100.00
calculator.compute_item(shipment) # => 15

Parameters:

  • object (Object)

    The object to calculate the discount for (e.g., LineItem, Shipment, ShippingRate)

Returns:

  • (BigDecimal)

    The discount amount, rounded to the order’s currency precision



45
46
47
48
# File 'app/models/solidus_promotions/calculators/percent.rb', line 45

def compute_item(object, _options = {})
  currency = object.respond_to?(:currency) ? object.currency : object.order.currency
  round_to_currency(object.discountable_amount * preferred_percent / 100, currency)
end