state_machines-activerecord 0.103.0 → 0.300.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 571fa09486dd051901ae113941b3ae04e9867da62da325c609f97f44f1272f66
4
- data.tar.gz: 22513e4df2238588d70dcff91f79fb00dfc18dac3a7b36a8a971765355939f8a
3
+ metadata.gz: 35ebef64fc42b8b51c00b272365a7fe80b493d82b120ea2a21f9fafef0a0c640
4
+ data.tar.gz: c0a5b6b98eecd70f374c16ba76a590b372edcb0225e117a34d8218418add0113
5
5
  SHA512:
6
- metadata.gz: a15cf9abb68277ce52ab35e139b15fa8ce6b28fb68424bcbcf840de0216267f7f58b62483c01b2cbd62df9694ba117dfee3b090e2b64692cfe9114396d64c0f2
7
- data.tar.gz: 97cb794b7e45222503e682641e80da05282f3593453979650431f35fa687831e9349dabe46ea7f2969dc2f95e9b3bc181cfc5860af17e3d57aefb72a8144a485
6
+ metadata.gz: d636b2fab507273bfd4c0c7b9aca089ce47803fa9de302871e0a31ce02fbeb63776c8f305d724ca1d26a896087f3cd1014c96fbdb13e747529fff2c81a9c9117
7
+ data.tar.gz: 0b8b2ffd5bd9af75a42ef34d15e3b24ae21a5f638a05eb698b463bea07a537aa362898c1d507b3ebe35c778830988e0351dc50af37cae196fefe1b7cd499404f
data/README.md CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  # StateMachines Active Record Integration
4
4
 
5
- The Active Record 7.2+ integration adds support for database transactions, automatically
5
+ The Active Record 8.0+ integration adds support for database transactions, automatically
6
6
  saving the record, named scopes, validation errors.
7
7
 
8
8
  ## Requirements
9
9
 
10
10
  - Ruby 3.2+
11
- - Rails 7.2+
11
+ - Rails 8.0+
12
12
 
13
13
  ## Installation
14
14
 
@@ -60,6 +60,116 @@ class Vehicle < ApplicationRecord
60
60
  end
61
61
  ```
62
62
 
63
+ ## State changes go through events
64
+
65
+ The only way to change a record's state through the model is an event:
66
+
67
+ ```ruby
68
+ vehicle.ignite # fire it
69
+ vehicle.ignite! # fire it, raising on refusal
70
+ vehicle.state_event = 'ignite' # queue it for the next save
71
+ vehicle.save
72
+ vehicle.update(state_event: 'ignite')
73
+ ```
74
+
75
+ Writing a *different* state directly raises
76
+ `StateMachines::DirectStateAssignment` before the value changes, whichever
77
+ writer is used: `state=`, mass assignment (`assign_attributes`, `new`,
78
+ `create`, `update`), an attribute alias, `record[:state] =`,
79
+ `write_attribute`, `update_attribute`, or a Rails enum bang method
80
+ (`processing!`). Assigning the state the record already holds (`:parked`,
81
+ `"parked"`, or the stored integer for integer-backed machines) is allowed and
82
+ runs nothing. The error names the machine, the attribute, both values, and
83
+ the alternatives below; a refused assignment is not an event refusal, so no
84
+ `<event>_refusal` reason is recorded.
85
+
86
+ ```ruby
87
+ vehicle = Vehicle.create! # parked
88
+ vehicle.state = 'idling' # => StateMachines::DirectStateAssignment
89
+ vehicle.update(state: 'idling', state_event: 'ignite')
90
+ # => StateMachines::DirectStateAssignment
91
+ ```
92
+
93
+ - New records can be built with their initial state (static, dynamic, or the
94
+ schema default), e.g. `Vehicle.new(state: 'parked')`, but not with another
95
+ one: `Vehicle.create!(state: 'idling')`, `create_with(state: 'idling')` and
96
+ an initializer block writing `idling` all raise.
97
+ - Callbacks are held to the same rule: a `before_transition`,
98
+ `after_transition`, `before_save` or `after_initialize` writing the state
99
+ raises. Only the machine's own writes (initialization, the transition's
100
+ write, rollback after a failure) are authorized, each for that single
101
+ write. Loading from the database, `reload`, `restore_attributes`, `dup`
102
+ and `becomes` keep the state they hold.
103
+ - As a backstop, `save`, `save!`, `save(validate: false)` and
104
+ `update_attribute` refuse to persist a state that changed without going
105
+ through the setter (an in-place mutation, a write to the attribute set),
106
+ and no queued event runs from such a state.
107
+ - `becomes` preserves the state without running transition callbacks, and
108
+ raises `StateMachines::PendingStateEvent` while an event attribute or a
109
+ transition prepared by validation is still queued.
110
+
111
+ ### Forms
112
+
113
+ Expose events, not states. Permit the event attribute and leave the state
114
+ attribute out of strong parameters:
115
+
116
+ ```ruby
117
+ def vehicle_params
118
+ params.require(:vehicle).permit(:name, :state_event)
119
+ end
120
+ ```
121
+
122
+ A form submitting `state` alongside (or instead of) `state_event` gets a
123
+ `DirectStateAssignment` instead of a silent state change.
124
+
125
+ ### Data repair
126
+
127
+ Raw persistence stays outside the state machine on purpose: no event is
128
+ inferred, no callback or validation runs.
129
+
130
+ ```ruby
131
+ vehicle.update_column(:state, 'idling')
132
+ Vehicle.where(id: ids).update_all(state: 'parked')
133
+ Vehicle.upsert_all(rows)
134
+ ActiveRecord::Base.connection.execute("UPDATE vehicles SET state = 'parked' WHERE ...")
135
+ ```
136
+
137
+ Other instances already loaded in memory keep their old state until you
138
+ `reload` them.
139
+
140
+ ### Initial state from the schema default
141
+
142
+ When a machine has no `initial:` option and its attribute has a schema
143
+ default (a database column default, or an Attributes API `default:`) that
144
+ names a defined state, that default is the initial state:
145
+
146
+ ```ruby
147
+ # db/schema.rb
148
+ create_table "accounts" do |t|
149
+ t.string "state", default: "active", null: false
150
+ end
151
+
152
+ class Account < ApplicationRecord
153
+ state_machine do
154
+ state :active, :suspended
155
+ event(:suspend) { transition active: :suspended }
156
+ end
157
+ end
158
+
159
+ Account.new.state # => "active"
160
+ Account.new.suspend # => true
161
+ ```
162
+
163
+ - An explicit static `initial:` always wins over the schema default (and the
164
+ "different default" warning is printed, as before).
165
+ - A dynamic `initial: ->(record) { ... }` only fills a blank attribute, so a
166
+ schema default keeps precedence over it; the warning is printed.
167
+ - The default is read when a record is built, not when the class is loaded,
168
+ so defining the machine before the table exists (e.g. while migrating) is
169
+ fine.
170
+ - A default that names no defined state is ignored: the initial state stays
171
+ `nil` and the "different default" warning is printed at class load.
172
+
63
173
  ### Scopes
64
174
  Usage of the generated scopes (assuming default column `state`):
65
175
 
@@ -119,7 +229,8 @@ When enum integration is detected, the gem automatically:
119
229
  order = Order.create(status: :pending)
120
230
  order.pending? # => true (Rails enum method)
121
231
  order.processing? # => false (Rails enum method)
122
- order.processing! # Sets status to :processing (Rails enum method)
232
+ order.processing! # => StateMachines::DirectStateAssignment (writes the state directly)
233
+ order.process # Fire the event instead
123
234
 
124
235
  Order.pending # Rails enum scope
125
236
  Order.processing # Rails enum scope
@@ -164,6 +275,66 @@ machine.state_machine_methods
164
275
  # => ["status_pending?", "status_processing?", "status_completed?", "status_cancelled?", ...]
165
276
  ```
166
277
 
278
+ ## Integer-backed state attributes
279
+
280
+ Integer columns whose states don't declare explicit values are converted
281
+ transparently: application code reads state names while the database stores
282
+ integers (mapped by definition order).
283
+
284
+ ```ruby
285
+ class Order < ApplicationRecord
286
+ state_machine :status, initial: :pending do
287
+ state :pending
288
+ state :approved
289
+
290
+ event :approve do
291
+ transition pending: :approved
292
+ end
293
+ end
294
+ end
295
+
296
+ order = Order.create!
297
+ order.approve!
298
+ order.status # => "approved"
299
+ # The database stores 1.
300
+ ```
301
+
302
+ Machines where every state declares an explicit integer value keep the classic
303
+ raw-integer behavior automatically: reads return the integer and `status_name`
304
+ returns the state name:
305
+
306
+ ```ruby
307
+ class LegacyOrder < ApplicationRecord
308
+ self.table_name = "orders"
309
+
310
+ state_machine :status, initial: :pending do
311
+ state :pending, value: 0
312
+ state :approved, value: 1
313
+
314
+ event :approve do
315
+ transition pending: :approved
316
+ end
317
+ end
318
+ end
319
+
320
+ order = LegacyOrder.create!
321
+ order.approve!
322
+ order.status # => 1
323
+ order.status_name # => :approved
324
+ # The database stores 1.
325
+ ```
326
+
327
+ Applications that want no type conversion at all can disable it during boot,
328
+ before defining affected state machines:
329
+
330
+ ```ruby
331
+ # config/initializers/state_machines.rb
332
+
333
+ StateMachines::Integrations::ActiveRecord.auto_convert_integer_state_attributes = false
334
+ ```
335
+
336
+ With this setting disabled, integer-backed state attributes are left entirely
337
+ to ActiveRecord's normal integer handling.
167
338
 
168
339
  ### Requirements for Enum Integration
169
340
 
@@ -210,6 +381,74 @@ class Vehicle < ApplicationRecord
210
381
  end
211
382
  ```
212
383
 
384
+ ## Transient state attributes
385
+
386
+ A machine can live on an attribute that is not a database column, either an
387
+ `attr_accessor` or an Attributes API `attribute` with no column behind it:
388
+
389
+ ```ruby
390
+ class Order < ApplicationRecord
391
+ attribute :stage, :string
392
+
393
+ state_machine :stage, initial: ->(order) { order.paid_at ? :paid : :open } do
394
+ state :open, :paid
395
+ end
396
+ end
397
+ ```
398
+
399
+ The initial state is applied to new records *and* to records loaded from the
400
+ database (loading skips `initialize`, so the integration fills the blank
401
+ attribute itself). That happens before `after_find`/`after_initialize`
402
+ callbacks run, so those see the initialized state and may fire events from it
403
+ (writing the state directly raises, as everywhere else). State-scoped validations run
404
+ as they do for column-backed machines, and the attribute's writer follows the
405
+ same [event-only rule](#state-changes-go-through-events) (there is no column,
406
+ so the raw-repair APIs do not apply). Machines on real columns are never
407
+ re-initialized on load: a `NULL` in the database stays `nil`.
408
+
409
+ ## Why an event was refused
410
+
411
+ An event method still returns `false` when it is refused, and `errors` is filled
412
+ as before. The `<event>_refusal` reader from state_machines tells the reasons
413
+ apart (`nil` after a success):
414
+
415
+ | Reason | When |
416
+ |------------------|--------------------------------------------------------------------------|
417
+ | `:no_transition` | No transition for the event from the current state |
418
+ | `:guard` | An `if:`/`unless:` rejected the transition |
419
+ | `:halted` | A `before_transition` returned `false`, or an `around_transition` did not yield |
420
+ | `:action_failed` | `save` returned `false` (validations, a `before_save` that throws `:abort`) or `save!` raised |
421
+
422
+ ```ruby
423
+ vehicle.shift_up # => false
424
+ vehicle.shift_up_refusal # => :action_failed
425
+ vehicle.errors.full_messages # => ["Seatbelt on can't be blank"]
426
+
427
+ vehicle.shift_up! # => StateMachines::InvalidTransition, #reason => :action_failed
428
+
429
+ # Event attributes record the reason too, including when save! raises
430
+ vehicle.state_event = 'shift_up'
431
+ vehicle.save! # => ActiveRecord::RecordInvalid
432
+ vehicle.shift_up_refusal # => :action_failed
433
+ ```
434
+
435
+ In parallel (`fire_events`) only the events that caused the refusal carry a
436
+ reason; a failed `save` is shared, so all of them read `:action_failed`.
437
+
438
+ When `save` fails because another machine's event attribute was refused inside
439
+ it, the fired event carries that reason, matching the bang message:
440
+
441
+ ```ruby
442
+ vehicle.alarm_state_event = 'disable' # its before_transition halts
443
+ vehicle.ignite # => false
444
+ vehicle.ignite_refusal # => :halted (not :action_failed)
445
+ ```
446
+
447
+ `reload` forgets the reasons, and a `dup` / `clone` starts without any. The
448
+ reader reports the most recent attempt on the record, so code firing events on
449
+ one record from several threads should rely on the bang method's
450
+ `InvalidTransition#reason` instead.
451
+
213
452
  ## Contributing
214
453
 
215
454
  1. Fork it ( https://github.com/state-machines/state_machines-activerecord/fork )
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ module StateMachines
4
+ # Raised when a state machine attribute of an ActiveRecord model is written
5
+ # directly with a different state: through its setter, mass assignment,
6
+ # an attribute alias, +record[:state] =+ or +write_attribute+, while
7
+ # building a record with a state other than its initial state, or when
8
+ # saving a state that was changed without going through the setter.
9
+ #
10
+ # State changes go through events. Raw persistence (+update_column+,
11
+ # +update_columns+, +update_all+, +insert_all+, SQL) stays outside the
12
+ # machine for data repair.
13
+ #
14
+ # A refused assignment is not an event refusal: no refusal reason is
15
+ # recorded for it.
16
+ #
17
+ # @example
18
+ # vehicle.state = 'idling'
19
+ # # => StateMachines::DirectStateAssignment: Cannot assign Vehicle#state
20
+ # # directly from "parked" to "idling" (state machine :state). ...
21
+ class DirectStateAssignment < Error
22
+ # @return [StateMachines::Machine] the machine owning the attribute
23
+ attr_reader :machine
24
+
25
+ # @return [Symbol] the machine's attribute
26
+ attr_reader :attribute
27
+
28
+ # @return [Object] the state value the record holds legitimately
29
+ attr_reader :from
30
+
31
+ # @return [Object] the requested (or bypassed) state value
32
+ attr_reader :to
33
+
34
+ # @param object [ActiveRecord::Base] the record being written
35
+ # @param machine [StateMachines::Machine] the machine owning the attribute
36
+ # @param from [Object] the state value the record holds legitimately
37
+ # @param to [Object] the requested (or bypassed) state value
38
+ def initialize(object, machine:, from:, to:)
39
+ @machine = machine
40
+ @attribute = machine.attribute
41
+ @from = from
42
+ @to = to
43
+
44
+ super(object, build_message(object))
45
+ end
46
+
47
+ private
48
+
49
+ # @param object [ActiveRecord::Base] the record being written
50
+ # @return [String] the error message
51
+ def build_message(object)
52
+ "Cannot assign #{object.class.name}##{attribute} directly from #{from.inspect} to #{to.inspect} " \
53
+ "(state machine #{machine.name.inspect}). State changes go through events: fire one " \
54
+ "(record.<event> / record.<event>!) or set #{machine.attribute(:event)} and save; in forms, " \
55
+ "permit #{machine.attribute(:event)}, not #{attribute}. For data repair outside the state " \
56
+ 'machine use update_column, update_columns, update_all or SQL (no callbacks run), ' \
57
+ 'then reload live instances.'
58
+ end
59
+ end
60
+
61
+ # Raised by +becomes+ while a record still has queued state machine work
62
+ # (a pending event attribute or a transition prepared by validation): the
63
+ # new instance would silently drop it.
64
+ class PendingStateEvent < Error
65
+ # @return [StateMachines::Machine] the machine with queued work
66
+ attr_reader :machine
67
+
68
+ # @return [Symbol, String] the queued event
69
+ attr_reader :event
70
+
71
+ # @param object [ActiveRecord::Base] the record being converted
72
+ # @param machine [StateMachines::Machine] the machine with queued work
73
+ # @param event [Symbol, String] the queued event
74
+ def initialize(object, machine, event)
75
+ @machine = machine
76
+ @event = event
77
+
78
+ super(object, "Cannot call becomes on #{object.class.name} while state machine #{machine.name.inspect} " \
79
+ "has queued work (#{machine.attribute(:event)} = #{event.inspect}); " \
80
+ 'save the record or clear the event first.')
81
+ end
82
+ end
83
+ end