Skip to content

Instantly share code, notes, and snippets.

@r3ap3r2004
Forked from BDQ/bogo.rb
Created February 11, 2012 01:31
Show Gist options
  • Save r3ap3r2004/1795011 to your computer and use it in GitHub Desktop.
Save r3ap3r2004/1795011 to your computer and use it in GitHub Desktop.
module Spree
class Calculator::Bogo < Calculator
preference :number_to_buy, :integer, :default => 1
preference :number_to_get, :integer, :default => 1
def self.description
"Buy One Get One"
end
def compute(order)
line_items = applicable_line_items(order)
prices = prices_from_line_items(line_items).sort
amount = prices.first(number_free(prices.size)).sum
amount == 0 ? nil : amount
end
private
def free_ratio
self.preferred_number_to_get.to_f / ( self.preferred_number_to_get + self.preferred_number_to_buy )
end
def applicable_line_items(order)
order.line_items.select{|li| li.product.respond_to?(:is_gift_card?) ? (not li.product.is_gift_card?) : true }
end
def prices_from_line_items(line_items)
line_items.inject([]) {|prices, li| prices.concat [li.price]*li.quantity }
end
def number_free(number_of_items)
(number_of_items * free_ratio).to_i
end
end
end
# register it inside application.rb with:
config.after_initialize do
config.spree.calculators.promotion_actions_create_adjustments << Spree::Calculator::Bogo
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment