Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Checkout
- attr_reader :items, :pricing_rules
- def initialize(pricing_rules)
- @pricing_rules = pricing_rules
- @items = []
- end
- def add(item)
- items.push item
- end
- def total
- process_rules
- items.sum { |item| item.cost_with_discount }
- end
- private
- def process_rules
- pricing_rules.each do |type, rule|
- items_by_rule = items.select { |item| item.type.to_sym == type }
- process_discount(rule[:action]) if items_by_rule.count >= rule[:min_count]
- end
- end
- def process_discount(action)
- case action
- when :each_PC_minus_20percent
- items.select { |item| item.type == 'PC' }.each { |item| item.cost_with_discount = item.cost - item.cost * 20 / 100 }
- when :plus_1_CC
- cc_items = items.select { |item| item.type == 'CC' }
- if cc_items.count > 1
- free_cc_items = cc_items.count / 2
- cc_items.first(free_cc_items).each { |item| item.cost_with_discount = 0 }
- end
- end
- end
- end
- class Item
- attr_reader :cost, :type
- attr_accessor :cost_with_discount
- def initialize(data)
- @type = data[:type]
- @name = data[:name]
- @cost = data[:cost]
- @cost_with_discount = data[:cost]
- end
- end
- pricing_rules = { PC: { min_count: 3, action: :each_PC_minus_20percent }, CC: { min_count: 1, action: :plus_1_CC } }
- co = Checkout.new(pricing_rules)
- items_data = [
- { type: 'CC', name: 'Кока-Кола', cost: 1.50 },
- { type: 'CC', name: 'Кока-Кола', cost: 1.50 },
- { type: 'PC', name: 'Пепси Кола', cost: 2.00 },
- { type: 'PC', name: 'Пепси Кола', cost: 2.00 },
- { type: 'PC', name: 'Пепси Кола', cost: 2.00 },
- { type: 'WA', name: 'Вода', cost: 0.85 }
- ]
- items_data.each do |item_data|
- co.add(Item.new(item_data))
- end
- p co.total
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement