Skip to content

Instantly share code, notes, and snippets.

@gamesover
Forked from ashleyconnor/ruby.rb
Created May 23, 2017 22:32
Show Gist options
  • Save gamesover/896b8769e18bc225cb99cc3ff02f1a4f to your computer and use it in GitHub Desktop.
Save gamesover/896b8769e18bc225cb99cc3ff02f1a4f to your computer and use it in GitHub Desktop.
Ruby Test Cart
require 'bigdecimal'
class Item
attr_accessor :code, :name, :price
def initialize(code, name, price)
@code = code
@name = name
@price = BigDecimal.new("#{price}")
end
end
class Promotion
def initialize
@promo_rules = Hash.new
end
def add_promotion_rule(name, rule)
@promo_rules[name] = rule
end
def remove_promotion_rule(name)
if @promo_rules.has_key?(name)
@promo_rules.delete(name)
else
puts "Promo rule not found"
end
end
def promo_rules
@promo_rules
end
end
class Checkout
def initialize(promotional_rules)
@cart = []
@promo_rules = promotional_rules.promo_rules #ugly
@cart_total = BigDecimal.new(0)
end
def scan(*item)
item.each {|item| @cart << item }
end
def apply_promo_rules
puts @promo_rules.to_s
@promo_rules.each_pair do |name,rule|
rule.call @cart
end
end
#This will shave trailing zeros but Rails has helpers for currency
def total
self.apply_promo_rules
@cart.each { |item| cart_total =+ item.price }
@cart_total.to_s
end
def cart
@cart
end
end
#Test run
item1 = Item.new('001', "Lavender heart", 9.25)
item2 = Item.new('002', "Personalised cufflinks", 45.00)
item3 = Item.new('003', "Kids T-Shirt", 19.95)
promotional_rules = Promotion.new
ten_percent_discount_over_sixty = Proc.new {
cart.each { |item| cart_total += item.price }
if cart_total >= 60.00
cart_total =- cart_total * 0.1
end
}
lavender_hearts_discount = Proc.new {
count = @cart.each do |item|
if item.code == '001'
count += 1
end
end
if count > 1
@cart.each do |item|
if item.code == '001' && item.price == 9.25
item.price = 8.50
end
end
else
item.price = 9.25
end
}
promotional_rules.add_promotion_rule("lavender", lavender_hearts_discount)
promotional_rules.add_promotion_rule("ten percent", ten_percent_discount_over_sixty)
co = Checkout.new(promotional_rules)
co.scan(item1, item2, item3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment