Skip to content

Instantly share code, notes, and snippets.

@r00k
Created May 7, 2012 19:56
Show Gist options
  • Save r00k/2629990 to your computer and use it in GitHub Desktop.
Save r00k/2629990 to your computer and use it in GitHub Desktop.
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