Created
May 7, 2012 19:56
-
-
Save r00k/2629990 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class ClaimApplier | |
def initialize(order, claims) | |
@order = order | |
@claims = claims | |
end | |
def apply | |
@claims.sort_by(&:expires_at).each do |claim| | |
apply_claim(claim) | |
end | |
save_changed_claims | |
end | |
private | |
def amount_to_apply(claim) | |
[claim.value_remaining, @order.balance].min | |
end | |
def apply_claim(claim) | |
amount = amount_to_apply(claim) | |
@order.balance -= amount | |
@order.claim_credit += amount | |
claim.value_remaining -= amount | |
create_redemption(claim, amount) | |
end | |
def create_redemption(claim, amount) | |
if amount != 0 | |
redemption = Redemption.new | |
redemption.claim = claim | |
redemption.order = @order | |
redemption.campaign = claim.campaign | |
redemption.value = amount | |
redemption.save! | |
end | |
end | |
def save_changed_claims | |
@claims.select(&:changed?).map(&:save) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment