Class: Workarea::Pricing::PriceDistributor
- Inherits:
-
Object
- Object
- Workarea::Pricing::PriceDistributor
- 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
-
.for_items(price, items) ⇒ PriceDistributor
Get an instance of PriceDistributor for a price and a given set of items.
Instance Method Summary collapse
-
#initialize(total_value, units) ⇒ PriceDistributor
constructor
A new instance of PriceDistributor.
-
#results ⇒ Hash
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.
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.
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
#results ⇒ Hash
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.
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 |