Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Start of DSL for shopping cart and sales from SCIL #7 by @TzipiZnavot, @eladsof & @avivby
describe 'cart' do
it 'allows discount after purchasing certain amount' do
product = Product.new('Snickers', 3)
cart = Cart.new
6.times { cart << product }
cart.when_buying(product).times(5).get(1).free()
cart.total.should == 5*3
end
end
Product = Struct.new(:name, :price)
class Rule
def initialize(product)
@product = product
end
def times(count)
@times = count
self
end
def get(benefit_count)
@benefit_count = benefit_count
self
end
def free
@discount = 1
self
end
def apply_for(products)
return @benefit_count * @product.price * @discount if applies_for? products
0
end
def applies_for?(products)
products.count {|p| p == @product} >= @times + @benefit_count
end
end
class Cart
def initialize
@products = []
@rules = []
end
def regular_total
@products.map(&:price).inject(&:+)
end
def benefits
@rules.map { |rule| rule.apply_for(@products) }.inject(&:+)
end
def total
regular_total - benefits
end
def <<(product)
@products << product
end
def when_buying(product)
rule = Rule.new(product)
@rules << rule
rule
end
end
@products.map { |p| p.price }.inject(&:+) can be written  @products.map(&:price).inject(&:+)

apply_for(products) can be
return @benif.....@discount if applies_for? products
0

Other than that - the Rule class seems kinda off but i can't quite put my finger on it...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment