Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. class Checkout
  2. attr_reader :items, :pricing_rules
  3.  
  4. def initialize(pricing_rules)
  5. @pricing_rules = pricing_rules
  6. @items = []
  7. end
  8.  
  9. def add(item)
  10. items.push item
  11. end
  12.  
  13. def total
  14. process_rules
  15. items.sum { |item| item.cost_with_discount }
  16. end
  17.  
  18. private
  19.  
  20. def process_rules
  21. pricing_rules.each do |type, rule|
  22. items_by_rule = items.select { |item| item.type.to_sym == type }
  23. process_discount(rule[:action]) if items_by_rule.count >= rule[:min_count]
  24. end
  25. end
  26.  
  27. def process_discount(action)
  28. case action
  29. when :each_PC_minus_20percent
  30. items.select { |item| item.type == 'PC' }.each { |item| item.cost_with_discount = item.cost - item.cost * 20 / 100 }
  31. when :plus_1_CC
  32. cc_items = items.select { |item| item.type == 'CC' }
  33. if cc_items.count > 1
  34. free_cc_items = cc_items.count / 2
  35. cc_items.first(free_cc_items).each { |item| item.cost_with_discount = 0 }
  36. end
  37. end
  38. end
  39. end
  40.  
  41. class Item
  42. attr_reader :cost, :type
  43. attr_accessor :cost_with_discount
  44.  
  45. def initialize(data)
  46. @type = data[:type]
  47. @name = data[:name]
  48. @cost = data[:cost]
  49. @cost_with_discount = data[:cost]
  50. end
  51. end
  52.  
  53. pricing_rules = { PC: { min_count: 3, action: :each_PC_minus_20percent }, CC: { min_count: 1, action: :plus_1_CC } }
  54. co = Checkout.new(pricing_rules)
  55. items_data = [
  56. { type: 'CC', name: 'Кока-Кола', cost: 1.50 },
  57. { type: 'CC', name: 'Кока-Кола', cost: 1.50 },
  58. { type: 'PC', name: 'Пепси Кола', cost: 2.00 },
  59. { type: 'PC', name: 'Пепси Кола', cost: 2.00 },
  60. { type: 'PC', name: 'Пепси Кола', cost: 2.00 },
  61. { type: 'WA', name: 'Вода', cost: 0.85 }
  62. ]
  63. items_data.each do |item_data|
  64. co.add(Item.new(item_data))
  65. end
  66.  
  67. p co.total
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement