class OfficeClerk::Post

Constants

DEFAULTS

Attributes

default_weight[R]
handling_fee[R]
handling_max[R]
max_item_weight[R]
max_price[R]
prices[R]
weights[R]

Public Class Methods

new(data) click to toggle source
Calls superclass method
# File lib/office_clerk/post.rb, line 12
def initialize data
  super DEFAULTS.merge(data)
  set_members
  check_values!
end

Public Instance Methods

available?(basket) click to toggle source

Determine if weight or size goes over bounds.

# File lib/office_clerk/post.rb, line 20
def available?(basket)
  basket.items.each do |item|
    if( weight = item.product.weight)
      return false if weight > max_item_weight
    end
  end
  true
end
price_for(basket) click to toggle source
# File lib/office_clerk/post.rb, line 29
def price_for(basket)
  total_price = basket.total_price
  return 0.0 if total_price > self.max_price
  total_weight = basket.items.map {|item| item.quantity * (item.product.weight || default_weight) }.reduce(:+) || 0.0
  shipping =  0

  while total_weight > weights.last # In several packets if need be.
    total_weight -= weights.last
    shipping += prices.last
  end

  [shipping, prices[compute_index(total_weight)], calc_handling_fee(total_price)].compact.sum
end

Private Instance Methods

calc_handling_fee(total_price) click to toggle source
# File lib/office_clerk/post.rb, line 54
def calc_handling_fee(total_price)
  handling_max < total_price ? 0 : handling_fee
end
check_values!() click to toggle source
# File lib/office_clerk/post.rb, line 67
def check_values!
  raise "Could not parse weights #{@weights}" if @weights.empty? or  @weights.include?(nil) 
  raise "Could not parse prices #{@prices}" if @prices.empty? or @prices.include?(nil)
  raise "Price length #{@prices.length} and weight length #{@weights.length} differ" if @weights.length != @prices.length
end
compute_index(total_weight) click to toggle source
# File lib/office_clerk/post.rb, line 45
def compute_index(total_weight)
  index = weights.length - 2
  while index >= 0
    break if total_weight > weights[index]
    index -= 1
  end
  index + 1
end
set_members() click to toggle source
# File lib/office_clerk/post.rb, line 58
def set_members
  @prices = @data[:price_table].split.map(&:to_f)
  @weights = @data[:weight_table].split.map(&:to_f)
  @max_item_weight = @data[:max_item_weight].to_f || 18.0
  @max_price = @data[:max_price].to_f || 100.0
  @handling_max = @data[:handling_max].to_f || 20.0
  @handling_fee = @data[:handling_fee].to_f || 2.0
  @default_weight = @data[:default_weight].to_f || 1.0
end