Created
March 23, 2011 05:18
-
-
Save abyx/882662 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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...