Module: LiteState

Extended by:
ActiveSupport::Concern
Defined in:
lib/lite_state.rb,
lib/lite_state/version.rb

Overview

LiteState is a lightweight state machine module for ActiveRecord models. It supports state transitions, optional guards, timestamps, and emits ActiveSupport::Notifications events for each transition outcome.

Examples:

Basic usage

class Order < ApplicationRecord
  include LiteState

  state_column :status

  enum status: { pending: 0, processing: 1, completed: 2, cancelled: 3 }

  transition :process, from: :pending, to: :processing, timestamp: true
  transition :complete, from: :processing, to: :completed, timestamp: :completed_at
  transition :cancel, from: [:pending, :processing], to: :cancelled
end

order = Order.create!(status: :pending)
order.process  # => true, updates status to :processing and processing_at timestamp
order.complete # => true, updates status to :completed and completed_at timestamp

With guards and callbacks

class Employee < ApplicationRecord
  include LiteState

  state_column :state

  enum state: { created: 0, invited: 1, enrolled: 2, suspended: 3, terminated: 4 }

  transition :reactivate,
             from: [:suspended, :terminated],
             to: :enrolled,
             timestamp: :enrolled_on,
             guard: :eligible_for_reactivation? do
    notify_employee(:reactivated)
    clear_suspension_reason
  end

  def eligible_for_reactivation?
    return true if suspended?
    return true unless terminated_on
    terminated_on >= 90.days.ago.to_date
  end
end

Defined Under Namespace

Classes: Error, TransitionError

Constant Summary collapse

VERSION =
"0.2.0"