lite_state 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.rubocop.yml +9 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/README.md +496 -0
- data/Rakefile +12 -0
- data/examples/ecommerce_order.rb +300 -0
- data/examples/employee_lifecycle.rb +131 -0
- data/lib/lite_state/version.rb +5 -0
- data/lib/lite_state.rb +276 -0
- data/sig/lite_state.rbs +4 -0
- metadata +145 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 375a8bef62fc1d451a7a4cae7bbd589eba8ffedf4e5422662a400f9a224ce502
|
|
4
|
+
data.tar.gz: 2599f632d670a64c71b14939c0fd1e32cbf60ae566f7a5e72cf7b163cfbddc35
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 3da2f1ce51df274359c820b20f7583dec5d466c59797f454756ee3f603ac60ecf056c4b657be2935ad936f0c5abd321e10b6fc3f6179f56a43cd646940d22bdb
|
|
7
|
+
data.tar.gz: 726a49fae3957ef12237fc8b772e195785ffb4c61f73adcb5e9e21c560fbc9723c82235fa6a17f198fc35a21b3803c422dfc7f5636ae8d660b4fac4b0b9f2a9a
|
data/.rubocop.yml
ADDED
data/CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
|
2
|
+
|
|
3
|
+
## Our Pledge
|
|
4
|
+
|
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
|
10
|
+
identity and orientation.
|
|
11
|
+
|
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
|
13
|
+
diverse, inclusive, and healthy community.
|
|
14
|
+
|
|
15
|
+
## Our Standards
|
|
16
|
+
|
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
|
18
|
+
community include:
|
|
19
|
+
|
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
|
24
|
+
and learning from the experience
|
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
|
26
|
+
community
|
|
27
|
+
|
|
28
|
+
Examples of unacceptable behavior include:
|
|
29
|
+
|
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
|
31
|
+
any kind
|
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
|
33
|
+
* Public or private harassment
|
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
|
35
|
+
without their explicit permission
|
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
|
37
|
+
professional setting
|
|
38
|
+
|
|
39
|
+
## Enforcement Responsibilities
|
|
40
|
+
|
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
|
44
|
+
or harmful.
|
|
45
|
+
|
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
|
49
|
+
decisions when appropriate.
|
|
50
|
+
|
|
51
|
+
## Scope
|
|
52
|
+
|
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
|
54
|
+
an individual is officially representing the community in public spaces.
|
|
55
|
+
Examples of representing our community include using an official email address,
|
|
56
|
+
posting via an official social media account, or acting as an appointed
|
|
57
|
+
representative at an online or offline event.
|
|
58
|
+
|
|
59
|
+
## Enforcement
|
|
60
|
+
|
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
|
62
|
+
reported to the community leaders responsible for enforcement at
|
|
63
|
+
[INSERT CONTACT METHOD].
|
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
|
65
|
+
|
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
|
67
|
+
reporter of any incident.
|
|
68
|
+
|
|
69
|
+
## Enforcement Guidelines
|
|
70
|
+
|
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
|
73
|
+
|
|
74
|
+
### 1. Correction
|
|
75
|
+
|
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
|
77
|
+
unprofessional or unwelcome in the community.
|
|
78
|
+
|
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
|
82
|
+
|
|
83
|
+
### 2. Warning
|
|
84
|
+
|
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
|
86
|
+
actions.
|
|
87
|
+
|
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
|
93
|
+
ban.
|
|
94
|
+
|
|
95
|
+
### 3. Temporary Ban
|
|
96
|
+
|
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
|
98
|
+
sustained inappropriate behavior.
|
|
99
|
+
|
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
|
101
|
+
communication with the community for a specified period of time. No public or
|
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
|
104
|
+
Violating these terms may lead to a permanent ban.
|
|
105
|
+
|
|
106
|
+
### 4. Permanent Ban
|
|
107
|
+
|
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
|
111
|
+
|
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
|
113
|
+
community.
|
|
114
|
+
|
|
115
|
+
## Attribution
|
|
116
|
+
|
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
|
118
|
+
version 2.1, available at
|
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
|
120
|
+
|
|
121
|
+
Community Impact Guidelines were inspired by
|
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
|
123
|
+
|
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
|
127
|
+
|
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/README.md
ADDED
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
# LiteState
|
|
2
|
+
|
|
3
|
+
A lightweight, powerful state machine for ActiveRecord models. LiteState provides a clean DSL for defining state transitions with guards, timestamps, and comprehensive event instrumentation.
|
|
4
|
+
|
|
5
|
+
## Why LiteState?
|
|
6
|
+
|
|
7
|
+
- **Minimal & Fast**: No complex dependencies or overhead
|
|
8
|
+
- **ActiveRecord Native**: Works seamlessly with Rails enums
|
|
9
|
+
- **Type-Safe**: Validates state definitions at load time
|
|
10
|
+
- **Observable**: Built-in ActiveSupport::Notifications for monitoring
|
|
11
|
+
- **Transaction-Safe**: Automatic rollback on failures
|
|
12
|
+
- **Production-Ready**: Comprehensive error handling and logging
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
Add this line to your application's Gemfile:
|
|
17
|
+
|
|
18
|
+
```ruby
|
|
19
|
+
gem 'lite_state'
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
And then execute:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
bundle install
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Or install it yourself as:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
gem install lite_state
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick Start
|
|
35
|
+
|
|
36
|
+
```ruby
|
|
37
|
+
class Order < ApplicationRecord
|
|
38
|
+
include LiteState
|
|
39
|
+
|
|
40
|
+
state_column :status
|
|
41
|
+
|
|
42
|
+
enum :status, { pending: "pending", processing: "processing", completed: "completed", cancelled: "cancelled" }
|
|
43
|
+
|
|
44
|
+
# Simple transition
|
|
45
|
+
transition :process, from: :pending, to: :processing
|
|
46
|
+
|
|
47
|
+
# With timestamp
|
|
48
|
+
transition :complete, from: :processing, to: :completed, timestamp: true
|
|
49
|
+
|
|
50
|
+
# From multiple states
|
|
51
|
+
transition :cancel, from: [:pending, :processing], to: :cancelled
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
order = Order.create!(status: :pending)
|
|
55
|
+
order.process # => true, status is now :processing
|
|
56
|
+
order.complete # => true, status is now :completed, completed_at is set
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Features
|
|
60
|
+
|
|
61
|
+
### 1. State Transitions
|
|
62
|
+
|
|
63
|
+
Define clean, declarative transitions:
|
|
64
|
+
|
|
65
|
+
```ruby
|
|
66
|
+
class Employee < ApplicationRecord
|
|
67
|
+
include LiteState
|
|
68
|
+
|
|
69
|
+
state_column :state
|
|
70
|
+
|
|
71
|
+
enum :state, { created: "created", invited: "invited", enrolled: "enrolled", suspended: "suspended", terminated: "terminated" }
|
|
72
|
+
|
|
73
|
+
transition :invite, from: :created, to: :invited
|
|
74
|
+
transition :enroll, from: :invited, to: :enrolled
|
|
75
|
+
transition :suspend, from: :enrolled, to: :suspended
|
|
76
|
+
transition :terminate, from: [:enrolled, :suspended], to: :terminated
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
employee = Employee.create!(state: :created)
|
|
80
|
+
employee.invite # => true
|
|
81
|
+
employee.enroll # => true
|
|
82
|
+
employee.state # => "enrolled"
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### 2. Automatic Timestamps
|
|
86
|
+
|
|
87
|
+
Track when state changes occur:
|
|
88
|
+
|
|
89
|
+
```ruby
|
|
90
|
+
# Auto-generate timestamp column: :completed_at
|
|
91
|
+
transition :complete, from: :processing, to: :completed, timestamp: true
|
|
92
|
+
|
|
93
|
+
# Custom timestamp column
|
|
94
|
+
transition :complete, from: :processing, to: :completed, timestamp: :finished_at
|
|
95
|
+
|
|
96
|
+
order.complete
|
|
97
|
+
order.completed_at # => 2025-01-15 10:30:00 UTC
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### 3. Guard Conditions
|
|
101
|
+
|
|
102
|
+
Prevent invalid transitions with business logic:
|
|
103
|
+
|
|
104
|
+
```ruby
|
|
105
|
+
class Employee < ApplicationRecord
|
|
106
|
+
include LiteState
|
|
107
|
+
|
|
108
|
+
state_column :state
|
|
109
|
+
enum :state, { suspended: "suspended", terminated: "terminated", enrolled: "enrolled" }
|
|
110
|
+
|
|
111
|
+
transition :reactivate,
|
|
112
|
+
from: [:suspended, :terminated],
|
|
113
|
+
to: :enrolled,
|
|
114
|
+
guard: :eligible_for_reactivation?
|
|
115
|
+
|
|
116
|
+
def eligible_for_reactivation?
|
|
117
|
+
return true if suspended?
|
|
118
|
+
return true unless terminated_on
|
|
119
|
+
terminated_on >= 90.days.ago.to_date
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
employee = Employee.create!(state: :terminated, terminated_on: 100.days.ago)
|
|
124
|
+
employee.reactivate # => raises LiteState::TransitionError (guard failed)
|
|
125
|
+
|
|
126
|
+
employee.update!(terminated_on: 30.days.ago)
|
|
127
|
+
employee.reactivate # => true
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Guards can also be lambdas:
|
|
131
|
+
|
|
132
|
+
```ruby
|
|
133
|
+
transition :approve,
|
|
134
|
+
from: :pending,
|
|
135
|
+
to: :approved,
|
|
136
|
+
guard: -> { approval_count >= 2 }
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### 4. Transition Callbacks
|
|
140
|
+
|
|
141
|
+
Execute logic after successful state changes:
|
|
142
|
+
|
|
143
|
+
```ruby
|
|
144
|
+
transition :enroll, from: :invited, to: :enrolled, timestamp: :enrolled_on do
|
|
145
|
+
send_welcome_email
|
|
146
|
+
provision_account
|
|
147
|
+
notify_team
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# Callback failures automatically rollback the transaction
|
|
151
|
+
transition :activate, from: :pending, to: :active do
|
|
152
|
+
result = external_api_call
|
|
153
|
+
raise "API failed" unless result.success?
|
|
154
|
+
end
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### 5. Query Transitions
|
|
158
|
+
|
|
159
|
+
Check if a transition is currently allowed:
|
|
160
|
+
|
|
161
|
+
```ruby
|
|
162
|
+
order = Order.create!(status: :pending)
|
|
163
|
+
|
|
164
|
+
order.can_transition?(:process) # => true
|
|
165
|
+
order.can_transition?(:complete) # => false (not in :processing state)
|
|
166
|
+
|
|
167
|
+
order.process
|
|
168
|
+
order.can_transition?(:complete) # => true
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
This respects both state requirements and guards:
|
|
172
|
+
|
|
173
|
+
```ruby
|
|
174
|
+
employee = Employee.create!(state: :terminated, terminated_on: 100.days.ago)
|
|
175
|
+
employee.can_transition?(:reactivate) # => false (guard fails)
|
|
176
|
+
|
|
177
|
+
employee.update!(terminated_on: 30.days.ago)
|
|
178
|
+
employee.can_transition?(:reactivate) # => true
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### 6. Event Instrumentation
|
|
182
|
+
|
|
183
|
+
LiteState publishes ActiveSupport::Notifications events for every transition:
|
|
184
|
+
|
|
185
|
+
```ruby
|
|
186
|
+
# Subscribe to successful transitions
|
|
187
|
+
ActiveSupport::Notifications.subscribe(/order\.process\.success/) do |*args|
|
|
188
|
+
event = ActiveSupport::Notifications::Event.new(*args)
|
|
189
|
+
|
|
190
|
+
puts "Order #{event.payload[:record_id]} processed"
|
|
191
|
+
puts "From: #{event.payload[:from_state]}"
|
|
192
|
+
puts "To: #{event.payload[:to_state]}"
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
# Subscribe to failures
|
|
196
|
+
ActiveSupport::Notifications.subscribe(/order\..*\.invalid/) do |*args|
|
|
197
|
+
event = ActiveSupport::Notifications::Event.new(*args)
|
|
198
|
+
Sentry.capture_message("Invalid transition attempted", extra: event.payload)
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
# Subscribe to all events for a model
|
|
202
|
+
ActiveSupport::Notifications.subscribe(/order\./) do |name, start, finish, id, payload|
|
|
203
|
+
Rails.logger.info("Event: #{name}, Payload: #{payload}")
|
|
204
|
+
end
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Event patterns:
|
|
208
|
+
- `{model}.{transition}.success` - Transition completed successfully
|
|
209
|
+
- `{model}.{transition}.invalid` - Transition not allowed (wrong state or guard failed)
|
|
210
|
+
- `{model}.{transition}.failed` - Transition failed (validation error, callback exception)
|
|
211
|
+
|
|
212
|
+
Payload includes:
|
|
213
|
+
```ruby
|
|
214
|
+
{
|
|
215
|
+
record: <ActiveRecord object>,
|
|
216
|
+
record_id: <UUID/ID>,
|
|
217
|
+
from_state: :pending,
|
|
218
|
+
to_state: :processing,
|
|
219
|
+
event: :process,
|
|
220
|
+
timestamp: <Time>
|
|
221
|
+
}
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
### 7. Multiple State Columns
|
|
225
|
+
|
|
226
|
+
LiteState supports models with **multiple enum columns**, allowing independent state machines for different aspects of your model:
|
|
227
|
+
|
|
228
|
+
```ruby
|
|
229
|
+
class Order < ApplicationRecord
|
|
230
|
+
include LiteState
|
|
231
|
+
|
|
232
|
+
enum :status, { pending: "pending", processing: "processing", completed: "completed", cancelled: "cancelled" }
|
|
233
|
+
enum :payment_status, { unpaid: "unpaid", paid: "paid", refunded: "refunded" }
|
|
234
|
+
enum :fulfillment_status, { unfulfilled: "unfulfilled", shipped: "shipped", delivered: "delivered" }
|
|
235
|
+
|
|
236
|
+
# Set default state column (optional)
|
|
237
|
+
state_column :status
|
|
238
|
+
|
|
239
|
+
# Status transitions (uses default column)
|
|
240
|
+
transition :process, from: :pending, to: :processing
|
|
241
|
+
transition :complete, from: :processing, to: :completed
|
|
242
|
+
transition :cancel, from: [:pending, :processing], to: :cancelled
|
|
243
|
+
|
|
244
|
+
# Payment transitions (explicit column)
|
|
245
|
+
transition :pay, from: :unpaid, to: :paid, column: :payment_status, timestamp: :paid_at
|
|
246
|
+
transition :refund, from: :paid, to: :refunded, column: :payment_status
|
|
247
|
+
|
|
248
|
+
# Fulfillment transitions (explicit column with guard)
|
|
249
|
+
transition :ship,
|
|
250
|
+
from: :unfulfilled,
|
|
251
|
+
to: :shipped,
|
|
252
|
+
column: :fulfillment_status,
|
|
253
|
+
timestamp: :shipped_at,
|
|
254
|
+
guard: :can_ship?
|
|
255
|
+
|
|
256
|
+
transition :deliver,
|
|
257
|
+
from: :shipped,
|
|
258
|
+
to: :delivered,
|
|
259
|
+
column: :fulfillment_status,
|
|
260
|
+
timestamp: true
|
|
261
|
+
|
|
262
|
+
def can_ship?
|
|
263
|
+
paid?
|
|
264
|
+
end
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
# Usage
|
|
268
|
+
order = Order.create!(
|
|
269
|
+
status: :pending,
|
|
270
|
+
payment_status: :unpaid,
|
|
271
|
+
fulfillment_status: :unfulfilled
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
order.process # Changes status to :processing
|
|
275
|
+
order.pay # Changes payment_status to :paid
|
|
276
|
+
order.ship # Changes fulfillment_status to :shipped (guard passes)
|
|
277
|
+
order.complete # Changes status to :completed
|
|
278
|
+
order.deliver # Changes fulfillment_status to :delivered
|
|
279
|
+
|
|
280
|
+
# Each column's state is independent
|
|
281
|
+
order.status # => "completed"
|
|
282
|
+
order.payment_status # => "paid"
|
|
283
|
+
order.fulfillment_status # => "delivered"
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
#### Without a Default Column
|
|
287
|
+
|
|
288
|
+
If you prefer to be explicit, you can omit `state_column` and specify `column:` for every transition:
|
|
289
|
+
|
|
290
|
+
```ruby
|
|
291
|
+
class Order < ApplicationRecord
|
|
292
|
+
include LiteState
|
|
293
|
+
|
|
294
|
+
enum :status, { pending: "pending", processing: "processing", completed: "completed" }
|
|
295
|
+
enum :payment_status, { unpaid: "unpaid", paid: "paid", refunded: "refunded" }
|
|
296
|
+
|
|
297
|
+
# All transitions must specify column
|
|
298
|
+
transition :process, from: :pending, to: :processing, column: :status
|
|
299
|
+
transition :pay, from: :unpaid, to: :paid, column: :payment_status
|
|
300
|
+
end
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
#### Benefits of Multiple Columns
|
|
304
|
+
|
|
305
|
+
- **Separation of Concerns**: Different aspects of your model (payment, shipping, approval) can have independent state machines
|
|
306
|
+
- **Parallel Workflows**: Process orders while waiting for payment, or handle refunds independently of fulfillment
|
|
307
|
+
- **Clear Intent**: Each transition explicitly states which aspect of the model it affects
|
|
308
|
+
- **Type Safety**: State validation happens per column at class load time
|
|
309
|
+
|
|
310
|
+
#### can_transition? with Multiple Columns
|
|
311
|
+
|
|
312
|
+
The `can_transition?` helper works seamlessly with multiple columns:
|
|
313
|
+
|
|
314
|
+
```ruby
|
|
315
|
+
order.can_transition?(:process) # Checks status column
|
|
316
|
+
order.can_transition?(:pay) # Checks payment_status column
|
|
317
|
+
order.can_transition?(:ship) # Checks fulfillment_status + guard
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
### 8. Error Handling
|
|
321
|
+
|
|
322
|
+
LiteState provides rich error objects:
|
|
323
|
+
|
|
324
|
+
```ruby
|
|
325
|
+
begin
|
|
326
|
+
order.process
|
|
327
|
+
rescue LiteState::TransitionError => e
|
|
328
|
+
e.record # => <Order id: 123>
|
|
329
|
+
e.from # => :completed
|
|
330
|
+
e.to # => :processing
|
|
331
|
+
e.event # => :process
|
|
332
|
+
e.message # => "Invalid transition: Order #123 from :completed -> :processing on process"
|
|
333
|
+
end
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
All transitions are wrapped in database transactions and automatically rollback on failure.
|
|
337
|
+
|
|
338
|
+
## Real-World Examples
|
|
339
|
+
|
|
340
|
+
See the [examples](examples/) directory for complete, production-ready implementations:
|
|
341
|
+
|
|
342
|
+
### [Employee Lifecycle](examples/employee_lifecycle.rb) (Single State Column)
|
|
343
|
+
|
|
344
|
+
A complete employee lifecycle management system demonstrating:
|
|
345
|
+
- Single state machine for employee status
|
|
346
|
+
- Invitation, enrollment, suspension, and termination flows
|
|
347
|
+
- Guard-based reactivation eligibility (90-day rule for terminated employees)
|
|
348
|
+
- Automatic notifications and access control
|
|
349
|
+
- PIN reset functionality
|
|
350
|
+
|
|
351
|
+
```ruby
|
|
352
|
+
employee = Employee.create!(state: :created)
|
|
353
|
+
employee.invite # Sends invitation
|
|
354
|
+
employee.enroll # Enrolls employee
|
|
355
|
+
employee.suspend # Disables access
|
|
356
|
+
employee.reactivate # Restores access (if eligible)
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
### [E-Commerce Order](examples/ecommerce_order.rb) (Multiple State Columns)
|
|
360
|
+
|
|
361
|
+
A sophisticated order system with three independent state machines:
|
|
362
|
+
- **Order lifecycle**: pending → processing → completed
|
|
363
|
+
- **Payment lifecycle**: unpaid → authorized → paid → refunded
|
|
364
|
+
- **Fulfillment lifecycle**: unfulfilled → preparing → shipped → delivered
|
|
365
|
+
|
|
366
|
+
Features cross-state-machine guards, automatic transitions, and comprehensive business rules.
|
|
367
|
+
|
|
368
|
+
```ruby
|
|
369
|
+
order.process # Start processing
|
|
370
|
+
order.capture_payment # Charge customer
|
|
371
|
+
order.ship_order # Send package
|
|
372
|
+
order.deliver_order # Mark delivered, auto-complete order
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
## Event Monitoring Example
|
|
376
|
+
|
|
377
|
+
Set up comprehensive monitoring:
|
|
378
|
+
|
|
379
|
+
```ruby
|
|
380
|
+
# config/initializers/event_subscribers.rb
|
|
381
|
+
|
|
382
|
+
# Success tracking
|
|
383
|
+
ActiveSupport::Notifications.subscribe(/employee\.\w+\.success/) do |*args|
|
|
384
|
+
event = ActiveSupport::Notifications::Event.new(*args)
|
|
385
|
+
payload = event.payload
|
|
386
|
+
|
|
387
|
+
Rails.logger.info(
|
|
388
|
+
"[EmployeeLifecycle] Employee ##{payload[:record_id]} transitioned: " \
|
|
389
|
+
"#{payload[:from_state]} -> #{payload[:to_state]} (#{payload[:event]})"
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
# Send to Slack, DataDog, etc.
|
|
393
|
+
SlackNotifier.notify(
|
|
394
|
+
channel: "#employee-lifecycle",
|
|
395
|
+
message: "Employee #{payload[:record].name} was #{payload[:event]}ed"
|
|
396
|
+
)
|
|
397
|
+
end
|
|
398
|
+
|
|
399
|
+
# Failure tracking
|
|
400
|
+
ActiveSupport::Notifications.subscribe(/employee\.\w+\.(invalid|failed)/) do |*args|
|
|
401
|
+
event = ActiveSupport::Notifications::Event.new(*args)
|
|
402
|
+
payload = event.payload
|
|
403
|
+
|
|
404
|
+
Sentry.capture_message(
|
|
405
|
+
"Employee lifecycle transition failed",
|
|
406
|
+
level: :warning,
|
|
407
|
+
extra: {
|
|
408
|
+
employee_id: payload[:record_id],
|
|
409
|
+
from_state: payload[:from_state],
|
|
410
|
+
to_state: payload[:to_state],
|
|
411
|
+
event: payload[:event]
|
|
412
|
+
},
|
|
413
|
+
tags: {
|
|
414
|
+
event_type: "lifecycle_transition_failed",
|
|
415
|
+
transition: payload[:event].to_s
|
|
416
|
+
}
|
|
417
|
+
)
|
|
418
|
+
end
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
## Testing
|
|
422
|
+
|
|
423
|
+
LiteState makes testing easy:
|
|
424
|
+
|
|
425
|
+
```ruby
|
|
426
|
+
RSpec.describe Order, type: :model do
|
|
427
|
+
describe "#process" do
|
|
428
|
+
it "transitions from pending to processing" do
|
|
429
|
+
order = create(:order, status: :pending)
|
|
430
|
+
|
|
431
|
+
expect { order.process }.to change { order.status }
|
|
432
|
+
.from("pending").to("processing")
|
|
433
|
+
end
|
|
434
|
+
|
|
435
|
+
it "sets processing_at timestamp" do
|
|
436
|
+
order = create(:order, status: :pending)
|
|
437
|
+
order.process
|
|
438
|
+
|
|
439
|
+
expect(order.processing_at).to be_present
|
|
440
|
+
end
|
|
441
|
+
|
|
442
|
+
it "fails when not in pending state" do
|
|
443
|
+
order = create(:order, status: :completed)
|
|
444
|
+
|
|
445
|
+
expect { order.process }.to raise_error(LiteState::TransitionError)
|
|
446
|
+
expect(order.reload.status).to eq("completed")
|
|
447
|
+
end
|
|
448
|
+
|
|
449
|
+
it "publishes success event" do
|
|
450
|
+
order = create(:order, status: :pending)
|
|
451
|
+
|
|
452
|
+
expect {
|
|
453
|
+
order.process
|
|
454
|
+
}.to have_published_event("order.process.success")
|
|
455
|
+
end
|
|
456
|
+
end
|
|
457
|
+
|
|
458
|
+
describe "#can_transition?" do
|
|
459
|
+
it "returns true for valid transitions" do
|
|
460
|
+
order = create(:order, status: :pending)
|
|
461
|
+
|
|
462
|
+
expect(order.can_transition?(:process)).to be true
|
|
463
|
+
expect(order.can_transition?(:complete)).to be false
|
|
464
|
+
end
|
|
465
|
+
end
|
|
466
|
+
end
|
|
467
|
+
```
|
|
468
|
+
|
|
469
|
+
## Best Practices
|
|
470
|
+
|
|
471
|
+
1. **Keep Guards Simple**: Guards should be fast, synchronous checks. Move complex logic to callbacks.
|
|
472
|
+
|
|
473
|
+
2. **Use Events for Monitoring**: Subscribe to transition events for logging, metrics, and alerts.
|
|
474
|
+
|
|
475
|
+
3. **Validate States at Boot**: LiteState validates states when the class loads, catching configuration errors early.
|
|
476
|
+
|
|
477
|
+
4. **Handle Failures Gracefully**: All transitions are wrapped in transactions and rollback automatically.
|
|
478
|
+
|
|
479
|
+
5. **Test State Transitions**: Use `can_transition?` to test guard logic independently.
|
|
480
|
+
|
|
481
|
+
## Requirements
|
|
482
|
+
|
|
483
|
+
- Ruby >= 3.4
|
|
484
|
+
- Rails >= 7.1 (ActiveRecord + ActiveSupport)
|
|
485
|
+
|
|
486
|
+
## Development
|
|
487
|
+
|
|
488
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
|
489
|
+
|
|
490
|
+
## Contributing
|
|
491
|
+
|
|
492
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/mundanecodes/lite_state.
|
|
493
|
+
|
|
494
|
+
## License
|
|
495
|
+
|
|
496
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|