Class: Workarea::Pricing::PriceDistributor

Inherits:
Object
  • Object
show all
Defined in:
app/models/workarea/pricing/price_distributor.rb

Overview

This class is responsible for evenly (or as best as possible) distributing a price across a variable number of units.

This is used to prevent rounding errors when adding price adjustments for order level prices across items.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(total_value, units) ⇒ PriceDistributor

Returns a new instance of PriceDistributor.



34
35
36
37
38
# File 'app/models/workarea/pricing/price_distributor.rb', line 34

def initialize(total_value, units)
  @total_value = total_value
  @units = units
  @total_price = units.sum { |u| u[:price] }
end

Class Method Details

.for_items(price, items) ⇒ PriceDistributor

Get an instance of Workarea::Pricing::PriceDistributor for a price and a given set of items. Transforms the items into an array of unit hashes, which are how this class calculates.

Parameters:

Returns:



22
23
24
25
26
27
28
29
30
31
32
# File 'app/models/workarea/pricing/price_distributor.rb', line 22

def self.for_items(price, items)
  units = []

  items.each do |item|
    item.quantity.times do
      units << { id: item.id, price: item.current_unit_price }
    end
  end

  new(price, units)
end

Instance Method Details

#resultsHash

The results of the distribution in a hash, where key is the unit id and value is the that id’s share of the price.

Returns:

  • (Hash)


46
47
48
49
50
51
52
# File 'app/models/workarea/pricing/price_distributor.rb', line 46

def results
  @results ||= if can_distribute?
                 distributed_results
               else
                 empty_results
               end
end