HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Coupon system optimization

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
optimizationsystemcoupon

Problem

I have the following code for my coupon system. It should work but I'm sure I can optimize it.

Any suggestions would be welcome.

@price_to_pay = @booking_request.guests * @table_offer.price_cents / 100
@remaining = @coupon.current_amount - @price_to_pay
if @remaining > 0
  @coupon.current_amount = @remaining
  @price_to_pay = 0
elsif @remaining = 0
  @coupon.current_amount = 0
  @price_to_pay = 0
elsif @remaining < 0
  @coupon.current_amount = @remaining
  @price_to_pay = @remaining * -1
end
coupon.save

Solution

I think this replicates the logic:

price = @booking_request.guests * @table_offer.price_cents / 100
@remaining = @coupon.current_amount - price
@coupon.current_amount = @remaining
@price_to_play = @remaining >= 0 ? 0 : -@remaining
coupon.save


Note that I avoid setting @price_to_play to a value and changing it afterwards, that kind of variable re-using makes code harder to understand.

Code Snippets

price = @booking_request.guests * @table_offer.price_cents / 100
@remaining = @coupon.current_amount - price
@coupon.current_amount = @remaining
@price_to_play = @remaining >= 0 ? 0 : -@remaining
coupon.save

Context

StackExchange Code Review Q#18913, answer score: 2

Revisions (0)

No revisions yet.