ruby
40 lines · 8 steps
Modeling subscription lifecycle in Rails
A Subscription model uses an enum, composable scopes, and guarded bang methods to manage billing state transitions.
Explained by
highlit
1class Subscription < ApplicationRecord
2 belongs_to :account
3
4 enum :status, {
5 trialing: 0,
6 active: 1,
7 past_due: 2,
8 canceled: 3,
9 expired: 4
10 }, default: :trialing, validate: true
11
12 scope :billable, -> { where(status: %i[active past_due]) }
13 scope :renewable, -> { active.where(cancel_at_period_end: false) }
14 scope :ending_soon, ->(window = 3.days) { active.where(current_period_end: ..window.from_now) }
15
16 def can_reactivate?
17 canceled? || expired?
18 end
19
20 def mark_past_due!
21 return if past_due?
22
23 update!(status: :past_due, delinquent_since: Time.current)
24 BillingMailer.with(subscription: self).payment_failed.deliver_later
25 end
26
27 def cancel!(immediately: false)
28 if immediately
29 update!(status: :canceled, canceled_at: Time.current, current_period_end: Time.current)
30 else
31 update!(cancel_at_period_end: true)
32 end
33 end
34
35 def reactivate!
36 raise ActiveRecord::RecordInvalid, self unless can_reactivate?
37
38 update!(status: :active, canceled_at: nil, cancel_at_period_end: false)
39 end
40end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A validated enum turns a status column into named predicates and value scopes for free.
- 2Scopes chain onto enum-generated scopes, letting you express business rules declaratively.
- 3Guarded bang methods keep invalid state transitions from ever hitting the database.
Related explainers
ruby
class InactiveAccountCleanup BATCH_SIZE = 500 INACTIVITY_THRESHOLD = 18.months
Batch-processing dormant users in Rails
batch-processing
activerecord
service-object
Intermediate
9 steps
ruby
class ArticleSerializer < ActiveModel::Serializer attributes :id, :title, :slug, :excerpt, :reading_time, :published_at, :url belongs_to :author, serializer: UserSerializer
Shaping API output with ActiveModel::Serializer in Rails
serialization
json api
computed attributes
Intermediate
9 steps
ruby
def collatz_lengths Enumerator.new do |y| n = 1 loop do
Building infinite sequences with lazy enumerators
lazy-evaluation
enumerators
infinite-sequences
Intermediate
8 steps
typescript
import { Component, computed, inject, signal } from '@angular/core'; import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; import { CommonModule } from '@angular/common';
Building a signup stepper in Angular
signals
reactive-forms
form-validation
Intermediate
10 steps
rust
use std::collections::HashMap; use std::fmt; #[derive(Debug)]
Parsing a config file with typed errors in Rust
error-handling
enums
parsing
Intermediate
9 steps
ruby
require "set" class FuzzySearch def initialize(candidates)
Building a ranked fuzzy search in Ruby
fuzzy-matching
levenshtein
ranking
Intermediate
9 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/modeling-subscription-lifecycle-in-rails-explained-ruby-49de/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.