ruby
51 lines · 10 steps
Safe coupon redemption in Rails
A Coupon model that validates, locks, and atomically records each redemption while enforcing expiry and usage limits.
Explained by
highlit
1class Coupon < ApplicationRecord
2 has_many :redemptions, dependent: :destroy
3
4 validates :code, presence: true, uniqueness: { case_sensitive: false }
5 validates :usage_limit, numericality: { greater_than: 0 }, allow_nil: true
6 validate :not_expired, on: :redeem
7 validate :under_usage_limit, on: :redeem
8
9 before_validation :normalize_code
10
11 scope :active, -> {
12 where("expires_at IS NULL OR expires_at > ?", Time.current)
13 .where(disabled_at: nil)
14 }
15
16 scope :redeemable, -> {
17 active.where(<<~SQL.squish, false)
18 usage_limit IS NULL OR redemption_count < usage_limit OR ?
19 SQL
20 }
21
22 def redeem!(order)
23 with_lock do
24 unless valid?(:redeem)
25 raise ActiveRecord::RecordInvalid, self
26 end
27
28 redemption = redemptions.create!(order: order)
29 increment!(:redemption_count)
30 redemption
31 end
32 end
33
34 private
35
36 def normalize_code
37 self.code = code.to_s.strip.upcase.presence
38 end
39
40 def not_expired
41 return if expires_at.blank? || expires_at.future?
42
43 errors.add(:base, "This coupon expired on #{expires_at.to_date.to_fs(:long)}")
44 end
45
46 def under_usage_limit
47 return if usage_limit.blank? || redemption_count < usage_limit
48
49 errors.add(:base, "This coupon has reached its usage limit")
50 end
51end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Contextual validations with `on:` let one model enforce different rules for different actions.
- 2Wrapping reads and writes in `with_lock` serializes concurrent redemptions so limits can't be overshot.
- 3Scopes can push complex eligibility logic into SQL, keeping queries efficient and reusable.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/safe-coupon-redemption-in-rails-explained-ruby-9f5e/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.