state_machines-activerecord 0.200.0 → 0.301.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: f022e63c2bfd6af186733c95cbfc19cb7f25dfff128c791e5199b1a3f4e6d760
4
- data.tar.gz: '094b3a2befdd974fa1828e9237f75f0a5a38319b7e38b56b8a3dda376a1e797d'
3
+ metadata.gz: 2a978e35d63388e62357e60d6a6e02776b65aa895f0dff425d00fc8da056f48f
4
+ data.tar.gz: 03bb42e39587a982d6579bc0bdba365ef0e21b2dbea825116bc217677da067a5
5
5
  SHA512:
6
- metadata.gz: cfb9f8bca11c37eeaff38ff0a237c2cc241986bba88ee4a8859199ea05ee7d06b4449da73574e0125f678de3082f3ba4e472f491f0efe9100fc2b585cac5e818
7
- data.tar.gz: 8fb449a5ead40d4cf43e92208d307bb34f557e9aae068cda123c968ded28aecfa7a97c416426b04f99afd2550a50b54f852bc6e04c5ab6dc4fef62199d5e615d
6
+ metadata.gz: 7838106f843f19188b991d5a4ce9c62a9fd8420dd50cb6dbf651d81310dd2cbd70b986b48b857c614b20ffc082988c8422343133a23559fd95c2b5c3b755c469
7
+ data.tar.gz: 7550030858f46cfa1221c550b2a33ae3fae7b0014e90836cfa538a96472c77010642339593ed91b3497afac62b3fb9561c31a6e29b7f802a359f298102137136
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,133 @@ class Vehicle < ApplicationRecord
60
60
  end
61
61
  ```
62
62
 
63
+ ## State changes go through events
64
+
65
+ Opt a machine in with `direct_assignment: :deny`:
66
+
67
+ ```ruby
68
+ class Vehicle < ActiveRecord::Base
69
+ state_machine initial: :parked, direct_assignment: :deny do
70
+ event(:ignite) { transition parked: :idling }
71
+ end
72
+ end
73
+ ```
74
+
75
+ Machines without the option use
76
+ `StateMachines::Integrations::ActiveRecord.direct_assignment`, which is
77
+ `:allow` (the attribute can be written directly). Set it to `:deny` in an
78
+ initializer to opt every machine in; a machine can still pass
79
+ `direct_assignment: :allow`. The default is read when a machine is defined,
80
+ so set it before your models load.
81
+
82
+ With `:deny`, the only way to change a record's state through the model is an event:
83
+
84
+ ```ruby
85
+ vehicle.ignite # fire it
86
+ vehicle.ignite! # fire it, raising on refusal
87
+ vehicle.state_event = 'ignite' # queue it for the next save
88
+ vehicle.save
89
+ vehicle.update(state_event: 'ignite')
90
+ ```
91
+
92
+ Writing a *different* state directly raises
93
+ `StateMachines::DirectStateAssignment` before the value changes, whichever
94
+ writer is used: `state=`, mass assignment (`assign_attributes`, `new`,
95
+ `create`, `update`), an attribute alias, `record[:state] =`,
96
+ `write_attribute`, `update_attribute`, or a Rails enum bang method
97
+ (`processing!`). Assigning the state the record already holds (`:parked`,
98
+ `"parked"`, or the stored integer for integer-backed machines) is allowed and
99
+ runs nothing. The error names the machine, the attribute, both values, and
100
+ the alternatives below; a refused assignment is not an event refusal, so no
101
+ `<event>_refusal` reason is recorded.
102
+
103
+ ```ruby
104
+ vehicle = Vehicle.create! # parked
105
+ vehicle.state = 'idling' # => StateMachines::DirectStateAssignment
106
+ vehicle.update(state: 'idling', state_event: 'ignite')
107
+ # => StateMachines::DirectStateAssignment
108
+ ```
109
+
110
+ - New records can be built with their initial state (static, dynamic, or the
111
+ schema default), e.g. `Vehicle.new(state: 'parked')`, but not with another
112
+ one: `Vehicle.create!(state: 'idling')`, `create_with(state: 'idling')` and
113
+ an initializer block writing `idling` all raise.
114
+ - Callbacks are held to the same rule: a `before_transition`,
115
+ `after_transition`, `before_save` or `after_initialize` writing the state
116
+ raises. Only the machine's own writes (initialization, the transition's
117
+ write, rollback after a failure) are authorized, each for that single
118
+ write. Loading from the database, `reload`, `restore_attributes`, `dup`
119
+ and `becomes` keep the state they hold.
120
+ - As a backstop, `save`, `save!`, `save(validate: false)` and
121
+ `update_attribute` refuse to persist a state that changed without going
122
+ through the setter (an in-place mutation, a write to the attribute set),
123
+ and no queued event runs from such a state.
124
+ - `becomes` preserves the state without running transition callbacks, and
125
+ raises `StateMachines::PendingStateEvent` while an event attribute or a
126
+ transition prepared by validation is still queued.
127
+
128
+ ### Forms
129
+
130
+ Expose events, not states. Permit the event attribute and leave the state
131
+ attribute out of strong parameters:
132
+
133
+ ```ruby
134
+ def vehicle_params
135
+ params.require(:vehicle).permit(:name, :state_event)
136
+ end
137
+ ```
138
+
139
+ A form submitting `state` alongside (or instead of) `state_event` gets a
140
+ `DirectStateAssignment` instead of a silent state change.
141
+
142
+ ### Data repair
143
+
144
+ Raw persistence stays outside the state machine on purpose: no event is
145
+ inferred, no callback or validation runs.
146
+
147
+ ```ruby
148
+ vehicle.update_column(:state, 'idling')
149
+ Vehicle.where(id: ids).update_all(state: 'parked')
150
+ Vehicle.upsert_all(rows)
151
+ ActiveRecord::Base.connection.execute("UPDATE vehicles SET state = 'parked' WHERE ...")
152
+ ```
153
+
154
+ Other instances already loaded in memory keep their old state until you
155
+ `reload` them.
156
+
157
+ ### Initial state from the schema default
158
+
159
+ When a machine has no `initial:` option and its attribute has a schema
160
+ default (a database column default, or an Attributes API `default:`) that
161
+ names a defined state, that default is the initial state:
162
+
163
+ ```ruby
164
+ # db/schema.rb
165
+ create_table "accounts" do |t|
166
+ t.string "state", default: "active", null: false
167
+ end
168
+
169
+ class Account < ApplicationRecord
170
+ state_machine do
171
+ state :active, :suspended
172
+ event(:suspend) { transition active: :suspended }
173
+ end
174
+ end
175
+
176
+ Account.new.state # => "active"
177
+ Account.new.suspend # => true
178
+ ```
179
+
180
+ - An explicit static `initial:` always wins over the schema default (and the
181
+ "different default" warning is printed, as before).
182
+ - A dynamic `initial: ->(record) { ... }` only fills a blank attribute, so a
183
+ schema default keeps precedence over it; the warning is printed.
184
+ - The default is read when a record is built, not when the class is loaded,
185
+ so defining the machine before the table exists (e.g. while migrating) is
186
+ fine.
187
+ - A default that names no defined state is ignored: the initial state stays
188
+ `nil` and the "different default" warning is printed at class load.
189
+
63
190
  ### Scopes
64
191
  Usage of the generated scopes (assuming default column `state`):
65
192
 
@@ -119,7 +246,8 @@ When enum integration is detected, the gem automatically:
119
246
  order = Order.create(status: :pending)
120
247
  order.pending? # => true (Rails enum method)
121
248
  order.processing? # => false (Rails enum method)
122
- order.processing! # Sets status to :processing (Rails enum method)
249
+ order.processing! # => writes the state directly; raises StateMachines::DirectStateAssignment with direct_assignment: :deny
250
+ order.process # Fire the event instead
123
251
 
124
252
  Order.pending # Rails enum scope
125
253
  Order.processing # Rails enum scope
@@ -175,11 +303,15 @@ class Order < ApplicationRecord
175
303
  state_machine :status, initial: :pending do
176
304
  state :pending
177
305
  state :approved
306
+
307
+ event :approve do
308
+ transition pending: :approved
309
+ end
178
310
  end
179
311
  end
180
312
 
181
313
  order = Order.create!
182
- order.status = :approved
314
+ order.approve!
183
315
  order.status # => "approved"
184
316
  # The database stores 1.
185
317
  ```
@@ -266,6 +398,74 @@ class Vehicle < ApplicationRecord
266
398
  end
267
399
  ```
268
400
 
401
+ ## Transient state attributes
402
+
403
+ A machine can live on an attribute that is not a database column, either an
404
+ `attr_accessor` or an Attributes API `attribute` with no column behind it:
405
+
406
+ ```ruby
407
+ class Order < ApplicationRecord
408
+ attribute :stage, :string
409
+
410
+ state_machine :stage, initial: ->(order) { order.paid_at ? :paid : :open } do
411
+ state :open, :paid
412
+ end
413
+ end
414
+ ```
415
+
416
+ The initial state is applied to new records *and* to records loaded from the
417
+ database (loading skips `initialize`, so the integration fills the blank
418
+ attribute itself). That happens before `after_find`/`after_initialize`
419
+ callbacks run, so those see the initialized state and may fire events from it
420
+ (writing the state directly raises, as everywhere else). State-scoped validations run
421
+ as they do for column-backed machines, and the attribute's writer follows the
422
+ same [event-only rule](#state-changes-go-through-events) (there is no column,
423
+ so the raw-repair APIs do not apply). Machines on real columns are never
424
+ re-initialized on load: a `NULL` in the database stays `nil`.
425
+
426
+ ## Why an event was refused
427
+
428
+ An event method still returns `false` when it is refused, and `errors` is filled
429
+ as before. The `<event>_refusal` reader from state_machines tells the reasons
430
+ apart (`nil` after a success):
431
+
432
+ | Reason | When |
433
+ |------------------|--------------------------------------------------------------------------|
434
+ | `:no_transition` | No transition for the event from the current state |
435
+ | `:guard` | An `if:`/`unless:` rejected the transition |
436
+ | `:halted` | A `before_transition` returned `false`, or an `around_transition` did not yield |
437
+ | `:action_failed` | `save` returned `false` (validations, a `before_save` that throws `:abort`) or `save!` raised |
438
+
439
+ ```ruby
440
+ vehicle.shift_up # => false
441
+ vehicle.shift_up_refusal # => :action_failed
442
+ vehicle.errors.full_messages # => ["Seatbelt on can't be blank"]
443
+
444
+ vehicle.shift_up! # => StateMachines::InvalidTransition, #reason => :action_failed
445
+
446
+ # Event attributes record the reason too, including when save! raises
447
+ vehicle.state_event = 'shift_up'
448
+ vehicle.save! # => ActiveRecord::RecordInvalid
449
+ vehicle.shift_up_refusal # => :action_failed
450
+ ```
451
+
452
+ In parallel (`fire_events`) only the events that caused the refusal carry a
453
+ reason; a failed `save` is shared, so all of them read `:action_failed`.
454
+
455
+ When `save` fails because another machine's event attribute was refused inside
456
+ it, the fired event carries that reason, matching the bang message:
457
+
458
+ ```ruby
459
+ vehicle.alarm_state_event = 'disable' # its before_transition halts
460
+ vehicle.ignite # => false
461
+ vehicle.ignite_refusal # => :halted (not :action_failed)
462
+ ```
463
+
464
+ `reload` forgets the reasons, and a `dup` / `clone` starts without any. The
465
+ reader reports the most recent attempt on the record, so code firing events on
466
+ one record from several threads should rely on the bang method's
467
+ `InvalidTransition#reason` instead.
468
+
269
469
  ## Contributing
270
470
 
271
471
  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
@@ -0,0 +1,456 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'state_machines/integrations/active_record/errors'
4
+
5
+ module StateMachines
6
+ module Integrations
7
+ module ActiveRecord
8
+ # Enforces that state changes through the model are event-only, for
9
+ # machines declared with <tt>direct_assignment: :deny</tt> (or all
10
+ # machines when ActiveRecord.direct_assignment is +:deny+). Machines
11
+ # allowing direct assignment (the default) are left alone.
12
+ #
13
+ # Every write of a machine's attribute through the model (setter, mass
14
+ # assignment, attribute alias, +record[:attr] =+, +write_attribute+) is
15
+ # checked before the value changes:
16
+ #
17
+ # * writes performed by the machine itself (initialization, a
18
+ # transition persisting its destination, a rollback) are authorized
19
+ # for the duration of that single write only, so callbacks running
20
+ # around a transition cannot overwrite the state;
21
+ # * assigning the value the record already holds (compared through the
22
+ # attribute's type, so +:parked+, +'parked'+ and an integer-backed
23
+ # +0+ are the same) is allowed and runs nothing;
24
+ # * anything else raises {StateMachines::DirectStateAssignment}.
25
+ #
26
+ # While a record is being built, assigned states are collected and,
27
+ # once the machines have initialized, must equal the initial state.
28
+ #
29
+ # As a backstop, saving a record whose state attribute changed without
30
+ # an authorized write (e.g. an in-place mutation or a write straight to
31
+ # the attribute set) raises the same error.
32
+ #
33
+ # Raw persistence (+update_column(s)+, +update_all+, +insert_all+,
34
+ # SQL) and database hydration / +reload+ never go through attribute
35
+ # writers and are left alone.
36
+ module StateGuard
37
+ # Names of attributes the machine is currently writing
38
+ AUTHORIZED_WRITES = :@_state_machines_authorized_writes
39
+
40
+ # Attribute name => last state value written by the machine
41
+ AUTHORIZED_STATES = :@_state_machines_authorized_states
42
+
43
+ # Attribute names assigned while the record is being built
44
+ CONSTRUCTION_WRITES = :@_state_machines_construction_writes
45
+
46
+ # Instance methods mixed into every model owning a state machine.
47
+ module RecordMethods
48
+ # Updates an attribute, refusing a direct change of a state machine
49
+ # attribute.
50
+ #
51
+ # @param attr_name [String, Symbol] attribute (or alias) name
52
+ # @param value [Object] the new value
53
+ # @raise [StateMachines::DirectStateAssignment]
54
+ def write_attribute(attr_name, value)
55
+ name = attr_name.to_s
56
+ StateGuard.check_write!(self, self.class.attribute_aliases[name] || name, value)
57
+ super
58
+ end
59
+
60
+ # @api private
61
+ # @see #write_attribute
62
+ def _write_attribute(attr_name, value)
63
+ StateGuard.check_write!(self, attr_name.to_s, value)
64
+ super
65
+ end
66
+
67
+ # Converts the record to another class, preserving its state.
68
+ #
69
+ # No transition callbacks run, and a state changed without an event
70
+ # stays unauthorized on the new instance.
71
+ #
72
+ # @param klass [Class] the class to convert to
73
+ # @return [ActiveRecord::Base] the converted record
74
+ # @raise [StateMachines::PendingStateEvent] while an event attribute
75
+ # or a transition prepared by validation is queued
76
+ def becomes(klass)
77
+ StateGuard.ensure_no_queued_work!(self)
78
+ super.tap { |became| StateGuard.copy_authorizations(self, became) }
79
+ end
80
+
81
+ # Duplicates the record with its state. Dirty tracking restarts on
82
+ # the copy, so the states the original holds legitimately are
83
+ # authorized on it; a state changed without an event is not.
84
+ #
85
+ # @param other [ActiveRecord::Base] the original record
86
+ # @return [void]
87
+ def initialize_dup(other)
88
+ legitimate = StateGuard.legitimate_states(other)
89
+ super
90
+ remove_instance_variable(AUTHORIZED_WRITES) if instance_variable_defined?(AUTHORIZED_WRITES)
91
+ instance_variable_set(AUTHORIZED_STATES, legitimate)
92
+ end
93
+
94
+ # Reloads the record, forgetting state authorizations: the reloaded
95
+ # attributes are the database's.
96
+ #
97
+ # @return [ActiveRecord::Base] the reloaded record
98
+ def reload(*)
99
+ super.tap { StateGuard.forget(self) }
100
+ end
101
+
102
+ # Forgets state authorizations once changes are persisted.
103
+ #
104
+ # @return [void]
105
+ def changes_applied
106
+ super
107
+ StateGuard.forget(self)
108
+ end
109
+
110
+ # Forgets state authorizations along with the dirty tracking.
111
+ #
112
+ # @return [void]
113
+ def clear_changes_information
114
+ super
115
+ StateGuard.forget(self)
116
+ end
117
+
118
+ private
119
+
120
+ # @see #write_attribute
121
+ def attribute=(attr_name, value)
122
+ StateGuard.check_write!(self, attr_name.to_s, value)
123
+ super
124
+ end
125
+
126
+ # Saves, first refusing state changes made without an event.
127
+ def create_or_update(...)
128
+ StateGuard.verify_persistable!(self)
129
+ super
130
+ end
131
+
132
+ # Checks again once +before_save+ callbacks have run.
133
+ def _create_record(...)
134
+ StateGuard.verify_persistable!(self)
135
+ super
136
+ end
137
+
138
+ # Checks again once +before_save+ callbacks have run.
139
+ def _update_record(...)
140
+ StateGuard.verify_persistable!(self)
141
+ super
142
+ end
143
+
144
+ # Restoring an attribute to its database value is a revert, not a
145
+ # state change, so the write is authorized.
146
+ def restore_attribute!(attr_name)
147
+ StateGuard.authorize(self, attr_name.to_s) { super }
148
+ end
149
+
150
+ # Forgets the authorization of an attribute whose change is cleared
151
+ # (e.g. by +update_columns+).
152
+ def clear_attribute_change(attr_name)
153
+ super
154
+ StateGuard.forget(self, attr_name.to_s)
155
+ end
156
+ end
157
+
158
+ # Guards the writers of machine attributes: the attribute itself,
159
+ # the column it aliases and every alias of that column, whether an
160
+ # ActiveRecord attribute or not (e.g. +attr_accessor+).
161
+ class WriterGuard < Module
162
+ # @return [Set<String>] the attributes whose writers are guarded,
163
+ # aliases resolved
164
+ attr_reader :targets
165
+
166
+ def initialize
167
+ super
168
+ @targets = Set.new
169
+ @writers = Set.new
170
+ end
171
+
172
+ # Guards the writer of +name+.
173
+ #
174
+ # @param name [String] an attribute or alias name
175
+ # @return [void]
176
+ def guard(name)
177
+ return unless @writers.add?(name)
178
+
179
+ define_method(:"#{name}=") do |value|
180
+ StateGuard.check_write!(self, self.class.attribute_aliases[name] || name, value)
181
+ super(value)
182
+ end
183
+ end
184
+ end
185
+
186
+ # Guards writers of aliases declared after the machine.
187
+ module AliasGuard
188
+ # @see ActiveRecord::AttributeMethods::ClassMethods#alias_attribute
189
+ def alias_attribute(new_name, old_name)
190
+ super.tap do
191
+ guard = StateGuard.writer_guard(self)
192
+ target = attribute_aliases.fetch(old_name.to_s, old_name.to_s)
193
+ guard.guard(new_name.to_s) if guard&.targets&.include?(target)
194
+ end
195
+ end
196
+ end
197
+
198
+ class << self
199
+ # Installs the guard on a model class for a machine.
200
+ #
201
+ # @param klass [Class] the model class
202
+ # @param attribute [Symbol] the machine's attribute
203
+ # @return [void]
204
+ def install(klass, attribute)
205
+ klass.include(RecordMethods) unless klass < RecordMethods
206
+ klass.singleton_class.prepend(AliasGuard) unless klass.singleton_class < AliasGuard
207
+ guard = writer_guard(klass) || WriterGuard.new.tap { |mod| klass.prepend(mod) }
208
+
209
+ name = attribute.to_s
210
+ target = klass.attribute_aliases.fetch(name, name)
211
+ guard.targets << target
212
+ [name, target, *klass.attribute_aliases.select { |_, aliased| aliased == target }.keys]
213
+ .each { |writer| guard.guard(writer) }
214
+ end
215
+
216
+ # @param klass [Class] a model class
217
+ # @return [WriterGuard, nil] the writer guard of the class
218
+ def writer_guard(klass)
219
+ klass.ancestors.find { |mod| mod.is_a?(WriterGuard) }
220
+ end
221
+
222
+ # Checks a write of attribute +name+ before it happens.
223
+ #
224
+ # @param record [ActiveRecord::Base] the record being written
225
+ # @param name [String] the attribute name, aliases resolved
226
+ # @param value [Object] the value being written
227
+ # @return [void]
228
+ # @raise [StateMachines::DirectStateAssignment] when the write
229
+ # changes the state of a machine without authorization
230
+ def check_write!(record, name, value)
231
+ machine = machine_for(record, name)
232
+ return unless machine
233
+ return if record.instance_variable_get(AUTHORIZED_WRITES)&.include?(name)
234
+
235
+ if (writes = record.instance_variable_get(CONSTRUCTION_WRITES))
236
+ writes << name
237
+ return
238
+ end
239
+
240
+ current = current_value(record, machine)
241
+ return if same_state?(record, machine, current, value)
242
+
243
+ raise DirectStateAssignment.new(record, machine: machine, from: current, to: value)
244
+ end
245
+
246
+ # Authorizes writes of attribute +name+ for the duration of the
247
+ # block, then remembers the written value as legitimate.
248
+ #
249
+ # @param record [ActiveRecord::Base] the record being written
250
+ # @param name [String] the attribute name, aliases resolved
251
+ # @return [Object] the block's result
252
+ def authorize(record, name)
253
+ writes = record.instance_variable_get(AUTHORIZED_WRITES) ||
254
+ record.instance_variable_set(AUTHORIZED_WRITES, Set.new)
255
+ added = writes.add?(name)
256
+ result = yield
257
+ machine = machine_for(record, name)
258
+ remember(record, name, current_value(record, machine)) if machine
259
+ result
260
+ ensure
261
+ writes.delete(name) if added
262
+ end
263
+
264
+ # Starts collecting state assignments made while building a record.
265
+ #
266
+ # @param record [ActiveRecord::Base] the record being built
267
+ # @return [void]
268
+ def begin_construction(record)
269
+ record.instance_variable_set(CONSTRUCTION_WRITES, Set.new)
270
+ end
271
+
272
+ # Stops collecting state assignments and checks that each assigned
273
+ # state equals the machine's initial state for the record (static,
274
+ # dynamic or schema-default).
275
+ #
276
+ # @param record [ActiveRecord::Base] the record being built
277
+ # @return [void]
278
+ # @raise [StateMachines::DirectStateAssignment] when a state other
279
+ # than the initial one was assigned
280
+ def finish_construction(record)
281
+ writes = record.instance_variable_get(CONSTRUCTION_WRITES)
282
+ record.instance_variable_set(CONSTRUCTION_WRITES, nil)
283
+ return if writes.nil? || writes.empty?
284
+
285
+ # Machines sharing an attribute (e.g. a public and a private
286
+ # machine) share its initial state, set on one of them
287
+ machines = record.class.state_machines.values.group_by { |machine| guarded_name(machine) }
288
+ machines.slice(*writes).each do |name, siblings|
289
+ machine = siblings.find { |sibling| sibling.initial_state(record) } || siblings.first
290
+ current = current_value(record, machine)
291
+ expected = machine.initial_state(record)&.value
292
+ next remember(record, name, current) if same_state?(record, machine, expected, current)
293
+
294
+ raise DirectStateAssignment.new(record, machine: machine, from: expected, to: current)
295
+ end
296
+ end
297
+
298
+ # Refuses to persist a state attribute that changed without an
299
+ # authorized write.
300
+ #
301
+ # @param record [ActiveRecord::Base] the record being saved
302
+ # @return [void]
303
+ # @raise [StateMachines::DirectStateAssignment]
304
+ def verify_persistable!(record)
305
+ each_persisted_state(record) do |machine, name, current, legitimate|
306
+ next if legitimate
307
+
308
+ from = record.attribute_in_database(name)
309
+ raise DirectStateAssignment.new(record, machine: machine, from: from, to: current)
310
+ end
311
+ end
312
+
313
+ # The persisted state attributes whose current value the record
314
+ # holds legitimately: unchanged, or last written by the machine.
315
+ #
316
+ # @param record [ActiveRecord::Base]
317
+ # @return [Hash{String => Object}] attribute name => current value
318
+ def legitimate_states(record)
319
+ states = {}
320
+ each_persisted_state(record) { |_machine, name, current, legitimate| states[name] = current if legitimate }
321
+ states
322
+ end
323
+
324
+ # Like {verify_persistable!}, but only while some machine has an
325
+ # event queued, so no transition starts from an unauthorized state.
326
+ #
327
+ # @param record [ActiveRecord::Base] the record about to transition
328
+ # @return [void]
329
+ def verify_before_transitions!(record)
330
+ verify_persistable!(record) if queued_work(record)
331
+ end
332
+
333
+ # @param record [ActiveRecord::Base] the record being converted
334
+ # @return [void]
335
+ # @raise [StateMachines::PendingStateEvent] when an event attribute
336
+ # or a prepared transition is queued
337
+ def ensure_no_queued_work!(record)
338
+ machine, event = queued_work(record)
339
+ raise PendingStateEvent.new(record, machine, event) if machine
340
+ end
341
+
342
+ # Gives +target+ the same state authorizations as +source+.
343
+ #
344
+ # @return [void]
345
+ def copy_authorizations(source, target)
346
+ target.instance_variable_set(AUTHORIZED_STATES, source.instance_variable_get(AUTHORIZED_STATES)&.dup)
347
+ end
348
+
349
+ # Forgets the remembered state of one or every attribute.
350
+ #
351
+ # @param record [ActiveRecord::Base]
352
+ # @param name [String, nil] the attribute, or nil for all
353
+ # @return [void]
354
+ def forget(record, name = nil)
355
+ authorized = record.instance_variable_get(AUTHORIZED_STATES)
356
+ return unless authorized
357
+
358
+ name ? authorized.delete(name) : authorized.clear
359
+ end
360
+
361
+ # The attribute a machine writes, aliases resolved.
362
+ #
363
+ # @param machine [StateMachines::Machine]
364
+ # @return [String]
365
+ def guarded_name(machine)
366
+ name = machine.attribute.to_s
367
+ machine.owner_class.attribute_aliases.fetch(name, name)
368
+ end
369
+
370
+ private
371
+
372
+ # Yields each database-backed state attribute of the record with
373
+ # its current value and whether the record holds it legitimately.
374
+ #
375
+ # @yieldparam machine [StateMachines::Machine]
376
+ # @yieldparam name [String] the attribute name, aliases resolved
377
+ # @yieldparam current [Object] the current value
378
+ # @yieldparam legitimate [Boolean] unchanged, or last written by
379
+ # the machine
380
+ # @return [void]
381
+ def each_persisted_state(record)
382
+ authorized = record.instance_variable_get(AUTHORIZED_STATES)
383
+ seen = Set.new
384
+
385
+ record.class.state_machines.each_value do |machine|
386
+ next unless machine.direct_assignment_denied?
387
+
388
+ name = guarded_name(machine)
389
+ next unless seen.add?(name) && record._has_attribute?(name) && !machine.transient_attribute?
390
+
391
+ current = record._read_attribute(name)
392
+ legitimate = !record.attribute_changed?(name) ||
393
+ (authorized&.key?(name) && same_state?(record, machine, authorized[name], current))
394
+ yield machine, name, current, legitimate
395
+ end
396
+ end
397
+
398
+ # @return [StateMachines::Machine, nil] the first machine writing
399
+ # attribute +name+ that denies direct assignment
400
+ def machine_for(record, name)
401
+ record.class.state_machines.each_value.find do |machine|
402
+ machine.direct_assignment_denied? && guarded_name(machine) == name
403
+ end
404
+ end
405
+
406
+ # @return [Array(StateMachines::Machine, Object), nil] the first
407
+ # machine with queued work and its event
408
+ def queued_work(record)
409
+ record.class.state_machines.each_value do |machine|
410
+ next unless machine.action
411
+
412
+ event = machine.read(record, :event)
413
+ event ||= machine.read(record, :event_transition, true)&.event
414
+ return [machine, event] if event
415
+ end
416
+ nil
417
+ end
418
+
419
+ # @return [Object] the current value of the machine's attribute
420
+ def current_value(record, machine)
421
+ name = guarded_name(machine)
422
+ record._has_attribute?(name) ? record._read_attribute(name) : record.public_send(machine.attribute)
423
+ end
424
+
425
+ # Whether two values denote the same stored state, compared through
426
+ # the attribute's type (symbols and strings, integer-backed states,
427
+ # enums).
428
+ #
429
+ # @return [Boolean]
430
+ def same_state?(record, machine, left, right)
431
+ canonical(record, machine, left) == canonical(record, machine, right)
432
+ end
433
+
434
+ # @return [Object] the value as the attribute would store it
435
+ def canonical(record, machine, value)
436
+ name = guarded_name(machine)
437
+ if record._has_attribute?(name)
438
+ record.class.type_for_attribute(name).cast(value)
439
+ else
440
+ value.is_a?(Symbol) ? value.to_s : value
441
+ end
442
+ end
443
+
444
+ # Remembers +value+ as the legitimate state of attribute +name+.
445
+ #
446
+ # @return [void]
447
+ def remember(record, name, value)
448
+ authorized = record.instance_variable_get(AUTHORIZED_STATES) ||
449
+ record.instance_variable_set(AUTHORIZED_STATES, {})
450
+ authorized[name] = value
451
+ end
452
+ end
453
+ end
454
+ end
455
+ end
456
+ end
@@ -3,7 +3,7 @@
3
3
  module StateMachines
4
4
  module Integrations
5
5
  module ActiveRecord
6
- VERSION = '0.200.0'
6
+ VERSION = '0.301.0'
7
7
  end
8
8
  end
9
9
  end
@@ -4,6 +4,7 @@ require 'state_machines-activemodel'
4
4
  require 'active_record'
5
5
  require 'state_machines/integrations/active_record/version'
6
6
  require 'state_machines/integrations/active_record/type/integer'
7
+ require 'state_machines/integrations/active_record/state_guard'
7
8
 
8
9
  module StateMachines
9
10
  module Integrations # :nodoc:
@@ -109,6 +110,40 @@ module StateMachines
109
110
  # # Control access via strong parameters in your controller
110
111
  # end
111
112
  #
113
+ # == Direct state assignment
114
+ #
115
+ # By default the machine's attribute can be written directly. Declare
116
+ # <tt>direct_assignment: :deny</tt> to make state changes through the
117
+ # model event-only:
118
+ #
119
+ # class Vehicle < ActiveRecord::Base
120
+ # state_machine initial: :parked, direct_assignment: :deny do
121
+ # event(:ignite) { transition parked: :idling }
122
+ # end
123
+ # end
124
+ #
125
+ # The default for machines that do not set the option is
126
+ # <tt>StateMachines::Integrations::ActiveRecord.direct_assignment</tt>
127
+ # (+:allow+); set it to +:deny+ to opt every machine in.
128
+ #
129
+ # With +:deny+, state changes through the model are event-only. Writing a different
130
+ # state directly (the attribute writer, mass assignment, an alias,
131
+ # <tt>record[:state] =</tt>, +write_attribute+, building a record with a
132
+ # non-initial state, or a callback doing any of these) raises
133
+ # StateMachines::DirectStateAssignment before the value changes, and
134
+ # +save+ refuses to persist a state changed behind the writer's back.
135
+ # Assigning the state the record already holds is allowed and runs
136
+ # nothing.
137
+ #
138
+ # vehicle = Vehicle.create # => #<Vehicle id: 1, name: nil, state: "parked">
139
+ # vehicle.state = 'idling' # => StateMachines::DirectStateAssignment
140
+ # vehicle.ignite # => true
141
+ #
142
+ # Raw persistence (+update_column+, +update_columns+, +update_all+,
143
+ # +insert_all+ / +upsert_all+, SQL) stays outside the machine for data
144
+ # repair: no event is inferred and no callback runs. Reload live
145
+ # instances afterwards. See StateGuard for the details.
146
+ #
112
147
  # == Transactions
113
148
  #
114
149
  # In order to ensure that any changes made during transition callbacks
@@ -183,7 +218,8 @@ module StateMachines
183
218
  #
184
219
  # For example,
185
220
  #
186
- # vehicle = Vehicle.create(:state => 'idling') # => #<Vehicle id: 1, name: nil, state: "idling">
221
+ # vehicle = Vehicle.create # => #<Vehicle id: 1, name: nil, state: "parked">
222
+ # vehicle.ignite # => true
187
223
  # vehicle.ignite # => false
188
224
  # vehicle.errors.full_messages # => ["State cannot transition via \"ignite\""]
189
225
  #
@@ -379,6 +415,22 @@ module StateMachines
379
415
  # The default options to use for state machines using this integration
380
416
  @defaults = { action: :save, use_transactions: true }
381
417
  @auto_convert_integer_state_attributes = true
418
+ @direct_assignment = :allow
419
+
420
+ # Values accepted by the +direct_assignment+ machine option
421
+ DIRECT_ASSIGNMENT_MODES = %i[allow deny].freeze
422
+
423
+ # Forgets the refusal reasons recorded on a record when it is reloaded:
424
+ # they describe attempts made against the state being discarded.
425
+ module RefusalReset
426
+ # Reloads the record and forgets its refusal reasons.
427
+ #
428
+ # @return [ActiveRecord::Base] the reloaded record
429
+ # @see StateMachines::Event#refusal
430
+ def reload(*)
431
+ super.tap { StateMachines::Event.clear_refusals(self) }
432
+ end
433
+ end
382
434
 
383
435
  # Machine-specific methods for enum integration
384
436
  module MachineMethods
@@ -401,14 +453,46 @@ module StateMachines
401
453
  # sees this machine's (cloned) states, picking up subclass-added states
402
454
  # as they are defined.
403
455
  #
456
+ # Also makes reload forget the record's refusal reasons (see
457
+ # {RefusalReset}) and installs the guard making state changes
458
+ # event-only (see {StateGuard}).
459
+ #
404
460
  # @param klass [Class] the new owner class
405
461
  # @return [Class] the assigned owner class
406
462
  def owner_class=(klass)
407
463
  super.tap do
464
+ klass.include(RefusalReset) unless klass < RefusalReset
465
+ StateGuard.install(klass, attribute) if direct_assignment_denied?
408
466
  register_integer_type if integer_type_registered?
409
467
  end
410
468
  end
411
469
 
470
+ # How direct writes of the machine's attribute are treated: +:allow+
471
+ # (they go through untouched) or +:deny+ (state changes are
472
+ # event-only, see {StateGuard}). Set per machine with the
473
+ # +direct_assignment+ option, defaulting to
474
+ # {ActiveRecord.direct_assignment}.
475
+ #
476
+ # @return [Symbol] +:allow+ or +:deny+
477
+ # @raise [ArgumentError] when the configured value is not a known mode
478
+ def direct_assignment
479
+ @direct_assignment ||= begin
480
+ mode = integration_options.fetch(:direct_assignment) { ActiveRecord.direct_assignment }
481
+ unless DIRECT_ASSIGNMENT_MODES.include?(mode)
482
+ raise ArgumentError,
483
+ "Invalid direct_assignment: #{mode.inspect} (expected one of #{DIRECT_ASSIGNMENT_MODES.inspect})"
484
+ end
485
+
486
+ mode
487
+ end
488
+ end
489
+
490
+ # @return [Boolean] whether state changes through the model are
491
+ # event-only
492
+ def direct_assignment_denied?
493
+ direct_assignment == :deny
494
+ end
495
+
412
496
  # Check if enum integration should be enabled for this machine
413
497
  def detect_enum_integration
414
498
  return nil unless owner_class.defined_enums.key?(attribute.to_s)
@@ -450,11 +534,64 @@ module StateMachines
450
534
  result
451
535
  end
452
536
 
537
+ # Sets the initial state, remembering whether one was configured
538
+ # explicitly. Without an explicit initial state the attribute's schema
539
+ # default may supply it (see {#initial_state}).
540
+ #
541
+ # @param new_initial_state [Symbol, Proc, nil] the initial state name,
542
+ # a lambda resolving it per record, or nil for none
543
+ # @return [Symbol, Proc, nil] the assigned initial state
544
+ def initial_state=(new_initial_state)
545
+ @explicit_initial_state = !new_initial_state.nil?
546
+ super
547
+ end
548
+
549
+ # Gets the initial state for the given record.
550
+ #
551
+ # An explicit +initial:+ (static or dynamic) always wins. Without one,
552
+ # the attribute's schema default (the database column default, or a
553
+ # default declared through the Attributes API) is used when it names a
554
+ # defined state. The default is read lazily, when a record is built, so
555
+ # defining the machine never requires the table to exist. A default
556
+ # that names no defined state is ignored and the initial state stays
557
+ # nil (the class-load conflicting-default warning reports it).
558
+ #
559
+ # @param object [ActiveRecord::Base] the record being initialized
560
+ # @return [StateMachines::State, nil] the initial state
561
+ def initial_state(object)
562
+ return super if explicit_initial_state?
563
+
564
+ schema_default_state || super
565
+ end
566
+
567
+ # Whether the machine's attribute is not backed by a database column
568
+ # (aliases resolve to their target). Reads the class's memoized
569
+ # columns, so it is cheap enough to call for every loaded record.
570
+ # Returns false while the schema cannot be read.
571
+ #
572
+ # @return [Boolean]
573
+ def transient_attribute?
574
+ name = attribute.to_s
575
+ !owner_class.columns_hash.key?(owner_class.attribute_aliases.fetch(name, name))
576
+ rescue ::ActiveRecord::StatementInvalid, ::ActiveRecord::ConnectionNotEstablished
577
+ false
578
+ end
579
+
580
+ # Whether the machine was given an explicit (non-nil) initial state.
581
+ #
582
+ # @return [Boolean]
583
+ def explicit_initial_state?
584
+ !!@explicit_initial_state
585
+ end
586
+
453
587
  # Warns at most once when the column default conflicts with the
454
588
  # machine's initial state. The conflict is re-evaluated as states are
455
- # defined, so remember when the warning has been issued.
589
+ # defined, so remember when the warning has been issued. No warning is
590
+ # issued when the machine has no explicit initial state and the column
591
+ # default names a defined state: the default then *is* the initial
592
+ # state.
456
593
  def check_conflicting_attribute_default
457
- return if @attribute_default_conflict_warned
594
+ return if @attribute_default_conflict_warned || schema_default_initial_state?
458
595
 
459
596
  initial_state = states.detect(&:initial)
460
597
  conflict = !owner_class_attribute_default.nil? && (
@@ -580,6 +717,31 @@ module StateMachines
580
717
  end
581
718
  end
582
719
 
720
+ # Writes a value to the record. A state write is the machine's own
721
+ # (initialization, a transition persisting its destination, a
722
+ # rollback), so it is authorized for the duration of this single
723
+ # write: callbacks running around it are not (see {StateGuard}).
724
+ #
725
+ # @param object [ActiveRecord::Base] record being written
726
+ # @param attr_sym [Symbol] attribute kind (:state, :event, ...)
727
+ # @param value [Object] the value to write
728
+ # @param ivar [Boolean] whether to write an instance variable
729
+ # @return [Object] the written value
730
+ def write(object, attr_sym, value, ivar = false)
731
+ return super unless attr_sym == :state && !ivar
732
+
733
+ StateGuard.authorize(object, StateGuard.guarded_name(self)) { super }
734
+ end
735
+
736
+ # Runs state events around validation, first refusing to start a
737
+ # transition from a state changed without an event.
738
+ #
739
+ # @param object [ActiveRecord::Base] record being validated
740
+ def around_validation(object, &)
741
+ StateGuard.verify_before_transitions!(object)
742
+ super
743
+ end
744
+
583
745
  # Machine internals (state matching, validations) call read() to get the
584
746
  # current state value and compare it against state.value. The custom
585
747
  # integer type already returns the canonical value when state values are
@@ -611,6 +773,24 @@ module StateMachines
611
773
 
612
774
  private
613
775
 
776
+ # Whether the schema default supplies the initial state: there is no
777
+ # explicit initial state and the default names a defined state.
778
+ #
779
+ # @return [Boolean]
780
+ def schema_default_initial_state?
781
+ !explicit_initial_state? && !schema_default_state.nil?
782
+ end
783
+
784
+ # Finds the named state matching the attribute's schema default.
785
+ #
786
+ # @return [StateMachines::State, nil] the matching state, or nil when
787
+ # there is no default (or no readable schema) or it names no state
788
+ def schema_default_state
789
+ return if owner_class_attribute_default.nil?
790
+
791
+ states.detect { |state| state.name && owner_class_attribute_default_matches?(state) }
792
+ end
793
+
614
794
  # Re-runs the conflicting-default check for states defined after
615
795
  # initialization. Skipped until an initial state exists (the DSL block
616
796
  # evaluates before initial_state= during Machine.new).
@@ -812,11 +992,42 @@ module StateMachines
812
992
  class << self
813
993
  attr_accessor :auto_convert_integer_state_attributes
814
994
 
995
+ # Default +direct_assignment+ mode for machines that do not set one:
996
+ # +:allow+ (default) or +:deny+. Read when a machine is defined.
997
+ #
998
+ # @return [Symbol]
999
+ attr_accessor :direct_assignment
1000
+
1001
+ # @return [Array<Symbol>] machine options added by this integration
1002
+ def integration_options
1003
+ [:direct_assignment]
1004
+ end
1005
+
815
1006
  # Classes that inherit from ActiveRecord::Base will automatically use
816
1007
  # the ActiveRecord integration.
817
1008
  def matching_ancestors
818
1009
  [::ActiveRecord::Base]
819
1010
  end
1011
+
1012
+ # Initializes the states of a record loaded from the database for the
1013
+ # machines whose attribute is not a database column (an
1014
+ # +attr_accessor+ or a column-less Attributes API attribute). Loading
1015
+ # skips +initialize+, so without this such records would start with a
1016
+ # blank state. Column-backed machines are left alone: the stored value,
1017
+ # even NULL, is the record's state. Only blank attributes are filled,
1018
+ # static initial states before dynamic ones (which may depend on them),
1019
+ # and before +after_find+/+after_initialize+ callbacks run, so those
1020
+ # callbacks see the initialized state (and may fire events from it).
1021
+ # The writes are the machine's own, so they are authorized (see
1022
+ # {StateGuard}) and run no callbacks.
1023
+ #
1024
+ # @param record [ActiveRecord::Base] the record being loaded
1025
+ # @return [void]
1026
+ def initialize_transient_states(record)
1027
+ machines = record.class.state_machines.values.select(&:transient_attribute?)
1028
+ static, dynamic = machines.partition { |machine| !machine.dynamic_initial_state? }
1029
+ (static + dynamic).each { |machine| machine.initialize_state(record) }
1030
+ end
820
1031
  end
821
1032
 
822
1033
  protected
@@ -826,14 +1037,20 @@ module StateMachines
826
1037
  action == :save
827
1038
  end
828
1039
 
829
- # Gets the db default for the machine's attribute.
830
- # For integer columns the raw pre-type-registration default is returned so
831
- # that check_conflicting_attribute_default can compare integers to integers.
1040
+ # Gets the db default for the machine's attribute, resolving attribute
1041
+ # aliases to the underlying column. For integer columns the raw
1042
+ # pre-type-registration default is returned so that
1043
+ # check_conflicting_attribute_default can compare integers to integers.
1044
+ # Returns nil while the schema cannot be read (no connection, no table).
1045
+ #
1046
+ # @return [Object, nil] the default value
832
1047
  def owner_class_attribute_default
833
1048
  return @raw_integer_column_default if defined?(@raw_integer_column_default)
834
1049
  return unless owner_class.connected? && owner_class.table_exists?
835
1050
 
836
- owner_class.column_defaults[attribute.to_s]
1051
+ owner_class.column_defaults[owner_class.attribute_aliases.fetch(attribute.to_s, attribute.to_s)]
1052
+ rescue ::ActiveRecord::StatementInvalid, ::ActiveRecord::ConnectionNotEstablished
1053
+ nil
837
1054
  end
838
1055
 
839
1056
  # Checks whether the given state matches the column default. When the
@@ -855,14 +1072,23 @@ module StateMachines
855
1072
  def define_state_initializer
856
1073
  define_helper :instance, <<-END_EVAL, __FILE__, __LINE__ + 1
857
1074
  def initialize(attributes = nil, *)
1075
+ StateMachines::Integrations::ActiveRecord::StateGuard.begin_construction(self)
858
1076
  super(attributes) do |*args|
859
1077
  attributes = (attributes || {}).transform_keys { |key| self.class.attribute_aliases[key.to_s] || key }
860
1078
  scoped_attributes = attributes.merge(self.class.scope_attributes)
861
1079
 
862
1080
  self.class.state_machines.initialize_states(self, {}, scoped_attributes)
1081
+ StateMachines::Integrations::ActiveRecord::StateGuard.finish_construction(self)
863
1082
  yield(*args) if block_given?
864
1083
  end
865
1084
  end
1085
+
1086
+ def init_with_attributes(attributes, new_record = false)
1087
+ super do |record|
1088
+ StateMachines::Integrations::ActiveRecord.initialize_transient_states(record)
1089
+ yield record if block_given?
1090
+ end
1091
+ end
866
1092
  END_EVAL
867
1093
  end
868
1094
 
@@ -890,6 +1116,7 @@ module StateMachines
890
1116
 
891
1117
  # Runs state events around the machine's :save action
892
1118
  def around_save(object, &)
1119
+ StateGuard.verify_before_transitions!(object)
893
1120
  # Pass fiber: false to avoid deadlocks with ActiveRecord's LoadInterlockAwareMonitor
894
1121
  object.class.state_machines.transitions(object, action, fiber: false).perform(&)
895
1122
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: state_machines-activerecord
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.200.0
4
+ version: 0.301.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih
@@ -16,28 +16,42 @@ dependencies:
16
16
  requirements:
17
17
  - - ">="
18
18
  - !ruby/object:Gem::Version
19
- version: '7.2'
19
+ version: '8.1'
20
20
  type: :runtime
21
21
  prerelease: false
22
22
  version_requirements: !ruby/object:Gem::Requirement
23
23
  requirements:
24
24
  - - ">="
25
25
  - !ruby/object:Gem::Version
26
- version: '7.2'
26
+ version: '8.1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: state_machines
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: 0.301.0
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: 0.301.0
27
41
  - !ruby/object:Gem::Dependency
28
42
  name: state_machines-activemodel
29
43
  requirement: !ruby/object:Gem::Requirement
30
44
  requirements:
31
45
  - - ">="
32
46
  - !ruby/object:Gem::Version
33
- version: 0.200.0
47
+ version: 0.300.0
34
48
  type: :runtime
35
49
  prerelease: false
36
50
  version_requirements: !ruby/object:Gem::Requirement
37
51
  requirements:
38
52
  - - ">="
39
53
  - !ruby/object:Gem::Version
40
- version: 0.200.0
54
+ version: 0.300.0
41
55
  - !ruby/object:Gem::Dependency
42
56
  name: appraisal
43
57
  requirement: !ruby/object:Gem::Requirement
@@ -56,16 +70,16 @@ dependencies:
56
70
  name: minitest
57
71
  requirement: !ruby/object:Gem::Requirement
58
72
  requirements:
59
- - - '='
73
+ - - "~>"
60
74
  - !ruby/object:Gem::Version
61
- version: 5.27.0
75
+ version: '6.0'
62
76
  type: :development
63
77
  prerelease: false
64
78
  version_requirements: !ruby/object:Gem::Requirement
65
79
  requirements:
66
- - - '='
80
+ - - "~>"
67
81
  - !ruby/object:Gem::Version
68
- version: 5.27.0
82
+ version: '6.0'
69
83
  - !ruby/object:Gem::Dependency
70
84
  name: minitest-reporters
71
85
  requirement: !ruby/object:Gem::Requirement
@@ -120,7 +134,9 @@ files:
120
134
  - README.md
121
135
  - lib/state_machines-activerecord.rb
122
136
  - lib/state_machines/integrations/active_record.rb
137
+ - lib/state_machines/integrations/active_record/errors.rb
123
138
  - lib/state_machines/integrations/active_record/locale.rb
139
+ - lib/state_machines/integrations/active_record/state_guard.rb
124
140
  - lib/state_machines/integrations/active_record/type/integer.rb
125
141
  - lib/state_machines/integrations/active_record/version.rb
126
142
  homepage: https://github.com/state-machines/state_machines-activerecord/
@@ -135,14 +151,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
135
151
  requirements:
136
152
  - - ">="
137
153
  - !ruby/object:Gem::Version
138
- version: '3.2'
154
+ version: '4.0'
139
155
  required_rubygems_version: !ruby/object:Gem::Requirement
140
156
  requirements:
141
157
  - - ">="
142
158
  - !ruby/object:Gem::Version
143
159
  version: '0'
144
160
  requirements: []
145
- rubygems_version: 4.0.10
161
+ rubygems_version: 4.0.20
146
162
  specification_version: 4
147
163
  summary: State machines Active Record Integration
148
164
  test_files: []