state_machines-activerecord 0.200.0 → 0.303.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: ffdd74d11d1cc866bd04554ef02a5942e9f84aced876586aa6015f9f686c1189
4
+ data.tar.gz: 0c3ad8ad2e0e57c23099c75eb0e8553505721630bb49608c58c513e9ce46391e
5
5
  SHA512:
6
- metadata.gz: cfb9f8bca11c37eeaff38ff0a237c2cc241986bba88ee4a8859199ea05ee7d06b4449da73574e0125f678de3082f3ba4e472f491f0efe9100fc2b585cac5e818
7
- data.tar.gz: 8fb449a5ead40d4cf43e92208d307bb34f557e9aae068cda123c968ded28aecfa7a97c416426b04f99afd2550a50b54f852bc6e04c5ab6dc4fef62199d5e615d
6
+ metadata.gz: 5b2bf0430eae8f198ee3c616790d862d1c55c238fb27449598abaaea7754df4356ca028ddf2be3ae15b3668993e2c86c4661795f6c72a261f0ce20444f594ef6
7
+ data.tar.gz: 1da6b7ad4b6f9a60235ea1de68d154e01dec66c1b0cc8ddb99cf9ca7301205799b1318de9da31b3783320dc945953bcf521e2064a3284b4fba18bdc12bb09ba9
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,147 @@ 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
+ `force_state!` moves a record to a state without firing an event and saves
145
+ it. Transition callbacks are skipped, but validations and save callbacks run,
146
+ so auditing (e.g. paper_trail) still records the change. It works whether or
147
+ not the machine denies direct assignment:
148
+
149
+ ```ruby
150
+ vehicle.force_state!(:parked)
151
+ vehicle.force_state!(:off, machine: :alarm_state) # required with several machines
152
+ ```
153
+
154
+ It raises `IndexError` for an unknown state, `StateMachines::PendingStateEvent`
155
+ while an event is queued, and `ActiveRecord::RecordInvalid` when the record is
156
+ invalid.
157
+
158
+ Raw persistence stays outside the state machine on purpose: no event is
159
+ inferred, no callback or validation runs.
160
+
161
+ ```ruby
162
+ vehicle.update_column(:state, 'idling')
163
+ Vehicle.where(id: ids).update_all(state: 'parked')
164
+ Vehicle.upsert_all(rows)
165
+ ActiveRecord::Base.connection.execute("UPDATE vehicles SET state = 'parked' WHERE ...")
166
+ ```
167
+
168
+ Other instances already loaded in memory keep their old state until you
169
+ `reload` them.
170
+
171
+ ### Initial state from the schema default
172
+
173
+ When a machine has no `initial:` option and its attribute has a schema
174
+ default (a database column default, or an Attributes API `default:`) that
175
+ names a defined state, that default is the initial state:
176
+
177
+ ```ruby
178
+ # db/schema.rb
179
+ create_table "accounts" do |t|
180
+ t.string "state", default: "active", null: false
181
+ end
182
+
183
+ class Account < ApplicationRecord
184
+ state_machine do
185
+ state :active, :suspended
186
+ event(:suspend) { transition active: :suspended }
187
+ end
188
+ end
189
+
190
+ Account.new.state # => "active"
191
+ Account.new.suspend # => true
192
+ ```
193
+
194
+ - An explicit `initial:`, static or dynamic, always wins over the schema
195
+ default (and the "different default" warning is printed). A dynamic one is
196
+ evaluated after the attributes given to `new` are assigned, so it can depend
197
+ on them; a state given to `new` is kept.
198
+ - The default is read when a record is built, not when the class is loaded,
199
+ so defining the machine before the table exists (e.g. while migrating) is
200
+ fine.
201
+ - A default that names no defined state is ignored: the initial state stays
202
+ `nil` and the "different default" warning is printed at class load.
203
+
63
204
  ### Scopes
64
205
  Usage of the generated scopes (assuming default column `state`):
65
206
 
@@ -119,7 +260,8 @@ When enum integration is detected, the gem automatically:
119
260
  order = Order.create(status: :pending)
120
261
  order.pending? # => true (Rails enum method)
121
262
  order.processing? # => false (Rails enum method)
122
- order.processing! # Sets status to :processing (Rails enum method)
263
+ order.processing! # => writes the state directly; raises StateMachines::DirectStateAssignment with direct_assignment: :deny
264
+ order.process # Fire the event instead
123
265
 
124
266
  Order.pending # Rails enum scope
125
267
  Order.processing # Rails enum scope
@@ -175,11 +317,15 @@ class Order < ApplicationRecord
175
317
  state_machine :status, initial: :pending do
176
318
  state :pending
177
319
  state :approved
320
+
321
+ event :approve do
322
+ transition pending: :approved
323
+ end
178
324
  end
179
325
  end
180
326
 
181
327
  order = Order.create!
182
- order.status = :approved
328
+ order.approve!
183
329
  order.status # => "approved"
184
330
  # The database stores 1.
185
331
  ```
@@ -266,6 +412,74 @@ class Vehicle < ApplicationRecord
266
412
  end
267
413
  ```
268
414
 
415
+ ## Transient state attributes
416
+
417
+ A machine can live on an attribute that is not a database column, either an
418
+ `attr_accessor` or an Attributes API `attribute` with no column behind it:
419
+
420
+ ```ruby
421
+ class Order < ApplicationRecord
422
+ attribute :stage, :string
423
+
424
+ state_machine :stage, initial: ->(order) { order.paid_at ? :paid : :open } do
425
+ state :open, :paid
426
+ end
427
+ end
428
+ ```
429
+
430
+ The initial state is applied to new records *and* to records loaded from the
431
+ database (loading skips `initialize`, so the integration fills the blank
432
+ attribute itself). That happens before `after_find`/`after_initialize`
433
+ callbacks run, so those see the initialized state and may fire events from it
434
+ (writing the state directly raises, as everywhere else). State-scoped validations run
435
+ as they do for column-backed machines, and the attribute's writer follows the
436
+ same [event-only rule](#state-changes-go-through-events) (there is no column,
437
+ so the raw-repair APIs do not apply). Machines on real columns are never
438
+ re-initialized on load: a `NULL` in the database stays `nil`.
439
+
440
+ ## Why an event was refused
441
+
442
+ An event method still returns `false` when it is refused, and `errors` is filled
443
+ as before. The `<event>_refusal` reader from state_machines tells the reasons
444
+ apart (`nil` after a success):
445
+
446
+ | Reason | When |
447
+ |------------------|--------------------------------------------------------------------------|
448
+ | `:no_transition` | No transition for the event from the current state |
449
+ | `:guard` | An `if:`/`unless:` rejected the transition |
450
+ | `:halted` | A `before_transition` returned `false`, or an `around_transition` did not yield |
451
+ | `:action_failed` | `save` returned `false` (validations, a `before_save` that throws `:abort`) or `save!` raised |
452
+
453
+ ```ruby
454
+ vehicle.shift_up # => false
455
+ vehicle.shift_up_refusal # => :action_failed
456
+ vehicle.errors.full_messages # => ["Seatbelt on can't be blank"]
457
+
458
+ vehicle.shift_up! # => StateMachines::InvalidTransition, #reason => :action_failed
459
+
460
+ # Event attributes record the reason too, including when save! raises
461
+ vehicle.state_event = 'shift_up'
462
+ vehicle.save! # => ActiveRecord::RecordInvalid
463
+ vehicle.shift_up_refusal # => :action_failed
464
+ ```
465
+
466
+ In parallel (`fire_events`) only the events that caused the refusal carry a
467
+ reason; a failed `save` is shared, so all of them read `:action_failed`.
468
+
469
+ When `save` fails because another machine's event attribute was refused inside
470
+ it, the fired event carries that reason, matching the bang message:
471
+
472
+ ```ruby
473
+ vehicle.alarm_state_event = 'disable' # its before_transition halts
474
+ vehicle.ignite # => false
475
+ vehicle.ignite_refusal # => :halted (not :action_failed)
476
+ ```
477
+
478
+ `reload` forgets the reasons, and a `dup` / `clone` starts without any. The
479
+ reader reports the most recent attempt on the record, so code firing events on
480
+ one record from several threads should rely on the bang method's
481
+ `InvalidTransition#reason` instead.
482
+
269
483
  ## Contributing
270
484
 
271
485
  1. Fork it ( https://github.com/state-machines/state_machines-activerecord/fork )
@@ -0,0 +1,85 @@
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+ or +force_state!+ while a record still has queued
62
+ # state machine work (a pending event attribute or a transition prepared by
63
+ # validation): +becomes+ would silently drop it, +force_state!+ would race
64
+ # it.
65
+ class PendingStateEvent < Error
66
+ # @return [StateMachines::Machine] the machine with queued work
67
+ attr_reader :machine
68
+
69
+ # @return [Symbol, String] the queued event
70
+ attr_reader :event
71
+
72
+ # @param object [ActiveRecord::Base] the record being converted
73
+ # @param machine [StateMachines::Machine] the machine with queued work
74
+ # @param event [Symbol, String] the queued event
75
+ # @param operation [String] the refused method
76
+ def initialize(object, machine, event, operation: 'becomes')
77
+ @machine = machine
78
+ @event = event
79
+
80
+ super(object, "Cannot call #{operation} on #{object.class.name} while state machine #{machine.name.inspect} " \
81
+ "has queued work (#{machine.attribute(:event)} = #{event.inspect}); " \
82
+ 'save the record or clear the event first.')
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module StateMachines
4
+ module Integrations
5
+ module ActiveRecord
6
+ # Administrative state changes outside the machine's events, mixed into
7
+ # every model owning a state machine.
8
+ module ForceState
9
+ # Moves the record to +state+ without firing an event, then saves it.
10
+ # No transition callbacks run, but validations and save callbacks do,
11
+ # so auditing (e.g. paper_trail) records the change. Works whether or
12
+ # not the machine denies direct assignment. Meant for data repair:
13
+ # regular state changes go through events.
14
+ #
15
+ # @param state [Symbol, String, nil] the target state's name
16
+ # @param machine [Symbol, String, nil] the machine's name; required
17
+ # when the model has several machines
18
+ # @return [true]
19
+ # @raise [ArgumentError] when +machine+ is missing or unknown
20
+ # @raise [IndexError] when +state+ is not a state of the machine
21
+ # @raise [StateMachines::PendingStateEvent] while an event attribute
22
+ # or a transition prepared by validation is queued
23
+ # @raise [ActiveRecord::RecordInvalid] when the record is invalid
24
+ def force_state!(state, machine: nil)
25
+ target = ForceState.machine_for(self, machine)
26
+ StateGuard.ensure_no_queued_work!(self, operation: 'force_state!')
27
+ target.write(self, :state, target.states.fetch(state).value)
28
+ save!
29
+ end
30
+
31
+ # @param record [ActiveRecord::Base] the record whose state is forced
32
+ # @param name [Symbol, String, nil] the requested machine's name
33
+ # @return [StateMachines::Machine] the machine to force
34
+ # @raise [ArgumentError] when +name+ is missing or unknown
35
+ def self.machine_for(record, name)
36
+ machines = record.class.state_machines
37
+ return machines.values.first if name.nil? && machines.size == 1
38
+
39
+ key = name&.to_sym
40
+ machines.fetch(key) do
41
+ names = machines.keys.map(&:inspect).join(', ')
42
+ raise ArgumentError, "#{record.class.name} has several state machines (#{names}); pass machine:" unless key
43
+
44
+ raise ArgumentError, "#{record.class.name} has no state machine #{key.inspect}"
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,457 @@
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 or forced
334
+ # @param operation [String] the refused method, named in the error
335
+ # @return [void]
336
+ # @raise [StateMachines::PendingStateEvent] when an event attribute
337
+ # or a prepared transition is queued
338
+ def ensure_no_queued_work!(record, operation: 'becomes')
339
+ machine, event = queued_work(record)
340
+ raise PendingStateEvent.new(record, machine, event, operation: operation) if machine
341
+ end
342
+
343
+ # Gives +target+ the same state authorizations as +source+.
344
+ #
345
+ # @return [void]
346
+ def copy_authorizations(source, target)
347
+ target.instance_variable_set(AUTHORIZED_STATES, source.instance_variable_get(AUTHORIZED_STATES)&.dup)
348
+ end
349
+
350
+ # Forgets the remembered state of one or every attribute.
351
+ #
352
+ # @param record [ActiveRecord::Base]
353
+ # @param name [String, nil] the attribute, or nil for all
354
+ # @return [void]
355
+ def forget(record, name = nil)
356
+ authorized = record.instance_variable_get(AUTHORIZED_STATES)
357
+ return unless authorized
358
+
359
+ name ? authorized.delete(name) : authorized.clear
360
+ end
361
+
362
+ # The attribute a machine writes, aliases resolved.
363
+ #
364
+ # @param machine [StateMachines::Machine]
365
+ # @return [String]
366
+ def guarded_name(machine)
367
+ name = machine.attribute.to_s
368
+ machine.owner_class.attribute_aliases.fetch(name, name)
369
+ end
370
+
371
+ private
372
+
373
+ # Yields each database-backed state attribute of the record with
374
+ # its current value and whether the record holds it legitimately.
375
+ #
376
+ # @yieldparam machine [StateMachines::Machine]
377
+ # @yieldparam name [String] the attribute name, aliases resolved
378
+ # @yieldparam current [Object] the current value
379
+ # @yieldparam legitimate [Boolean] unchanged, or last written by
380
+ # the machine
381
+ # @return [void]
382
+ def each_persisted_state(record)
383
+ authorized = record.instance_variable_get(AUTHORIZED_STATES)
384
+ seen = Set.new
385
+
386
+ record.class.state_machines.each_value do |machine|
387
+ next unless machine.direct_assignment_denied?
388
+
389
+ name = guarded_name(machine)
390
+ next unless seen.add?(name) && record._has_attribute?(name) && !machine.transient_attribute?
391
+
392
+ current = record._read_attribute(name)
393
+ legitimate = !record.attribute_changed?(name) ||
394
+ (authorized&.key?(name) && same_state?(record, machine, authorized[name], current))
395
+ yield machine, name, current, legitimate
396
+ end
397
+ end
398
+
399
+ # @return [StateMachines::Machine, nil] the first machine writing
400
+ # attribute +name+ that denies direct assignment
401
+ def machine_for(record, name)
402
+ record.class.state_machines.each_value.find do |machine|
403
+ machine.direct_assignment_denied? && guarded_name(machine) == name
404
+ end
405
+ end
406
+
407
+ # @return [Array(StateMachines::Machine, Object), nil] the first
408
+ # machine with queued work and its event
409
+ def queued_work(record)
410
+ record.class.state_machines.each_value do |machine|
411
+ next unless machine.action
412
+
413
+ event = machine.read(record, :event)
414
+ event ||= machine.read(record, :event_transition, true)&.event
415
+ return [machine, event] if event
416
+ end
417
+ nil
418
+ end
419
+
420
+ # @return [Object] the current value of the machine's attribute
421
+ def current_value(record, machine)
422
+ name = guarded_name(machine)
423
+ record._has_attribute?(name) ? record._read_attribute(name) : record.public_send(machine.attribute)
424
+ end
425
+
426
+ # Whether two values denote the same stored state, compared through
427
+ # the attribute's type (symbols and strings, integer-backed states,
428
+ # enums).
429
+ #
430
+ # @return [Boolean]
431
+ def same_state?(record, machine, left, right)
432
+ canonical(record, machine, left) == canonical(record, machine, right)
433
+ end
434
+
435
+ # @return [Object] the value as the attribute would store it
436
+ def canonical(record, machine, value)
437
+ name = guarded_name(machine)
438
+ if record._has_attribute?(name)
439
+ record.class.type_for_attribute(name).cast(value)
440
+ else
441
+ value.is_a?(Symbol) ? value.to_s : value
442
+ end
443
+ end
444
+
445
+ # Remembers +value+ as the legitimate state of attribute +name+.
446
+ #
447
+ # @return [void]
448
+ def remember(record, name, value)
449
+ authorized = record.instance_variable_get(AUTHORIZED_STATES) ||
450
+ record.instance_variable_set(AUTHORIZED_STATES, {})
451
+ authorized[name] = value
452
+ end
453
+ end
454
+ end
455
+ end
456
+ end
457
+ 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.303.0'
7
7
  end
8
8
  end
9
9
  end
@@ -4,6 +4,8 @@ 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'
8
+ require 'state_machines/integrations/active_record/force_state'
7
9
 
8
10
  module StateMachines
9
11
  module Integrations # :nodoc:
@@ -109,6 +111,40 @@ module StateMachines
109
111
  # # Control access via strong parameters in your controller
110
112
  # end
111
113
  #
114
+ # == Direct state assignment
115
+ #
116
+ # By default the machine's attribute can be written directly. Declare
117
+ # <tt>direct_assignment: :deny</tt> to make state changes through the
118
+ # model event-only:
119
+ #
120
+ # class Vehicle < ActiveRecord::Base
121
+ # state_machine initial: :parked, direct_assignment: :deny do
122
+ # event(:ignite) { transition parked: :idling }
123
+ # end
124
+ # end
125
+ #
126
+ # The default for machines that do not set the option is
127
+ # <tt>StateMachines::Integrations::ActiveRecord.direct_assignment</tt>
128
+ # (+:allow+); set it to +:deny+ to opt every machine in.
129
+ #
130
+ # With +:deny+, state changes through the model are event-only. Writing a different
131
+ # state directly (the attribute writer, mass assignment, an alias,
132
+ # <tt>record[:state] =</tt>, +write_attribute+, building a record with a
133
+ # non-initial state, or a callback doing any of these) raises
134
+ # StateMachines::DirectStateAssignment before the value changes, and
135
+ # +save+ refuses to persist a state changed behind the writer's back.
136
+ # Assigning the state the record already holds is allowed and runs
137
+ # nothing.
138
+ #
139
+ # vehicle = Vehicle.create # => #<Vehicle id: 1, name: nil, state: "parked">
140
+ # vehicle.state = 'idling' # => StateMachines::DirectStateAssignment
141
+ # vehicle.ignite # => true
142
+ #
143
+ # Raw persistence (+update_column+, +update_columns+, +update_all+,
144
+ # +insert_all+ / +upsert_all+, SQL) stays outside the machine for data
145
+ # repair: no event is inferred and no callback runs. Reload live
146
+ # instances afterwards. See StateGuard for the details.
147
+ #
112
148
  # == Transactions
113
149
  #
114
150
  # In order to ensure that any changes made during transition callbacks
@@ -183,7 +219,8 @@ module StateMachines
183
219
  #
184
220
  # For example,
185
221
  #
186
- # vehicle = Vehicle.create(:state => 'idling') # => #<Vehicle id: 1, name: nil, state: "idling">
222
+ # vehicle = Vehicle.create # => #<Vehicle id: 1, name: nil, state: "parked">
223
+ # vehicle.ignite # => true
187
224
  # vehicle.ignite # => false
188
225
  # vehicle.errors.full_messages # => ["State cannot transition via \"ignite\""]
189
226
  #
@@ -379,6 +416,22 @@ module StateMachines
379
416
  # The default options to use for state machines using this integration
380
417
  @defaults = { action: :save, use_transactions: true }
381
418
  @auto_convert_integer_state_attributes = true
419
+ @direct_assignment = :allow
420
+
421
+ # Values accepted by the +direct_assignment+ machine option
422
+ DIRECT_ASSIGNMENT_MODES = %i[allow deny].freeze
423
+
424
+ # Forgets the refusal reasons recorded on a record when it is reloaded:
425
+ # they describe attempts made against the state being discarded.
426
+ module RefusalReset
427
+ # Reloads the record and forgets its refusal reasons.
428
+ #
429
+ # @return [ActiveRecord::Base] the reloaded record
430
+ # @see StateMachines::Event#refusal
431
+ def reload(*)
432
+ super.tap { StateMachines::Event.clear_refusals(self) }
433
+ end
434
+ end
382
435
 
383
436
  # Machine-specific methods for enum integration
384
437
  module MachineMethods
@@ -401,14 +454,47 @@ module StateMachines
401
454
  # sees this machine's (cloned) states, picking up subclass-added states
402
455
  # as they are defined.
403
456
  #
457
+ # Also makes reload forget the record's refusal reasons (see
458
+ # {RefusalReset}) and installs the guard making state changes
459
+ # event-only (see {StateGuard}).
460
+ #
404
461
  # @param klass [Class] the new owner class
405
462
  # @return [Class] the assigned owner class
406
463
  def owner_class=(klass)
407
464
  super.tap do
465
+ klass.include(RefusalReset) unless klass < RefusalReset
466
+ klass.include(ForceState) unless klass < ForceState
467
+ StateGuard.install(klass, attribute) if direct_assignment_denied?
408
468
  register_integer_type if integer_type_registered?
409
469
  end
410
470
  end
411
471
 
472
+ # How direct writes of the machine's attribute are treated: +:allow+
473
+ # (they go through untouched) or +:deny+ (state changes are
474
+ # event-only, see {StateGuard}). Set per machine with the
475
+ # +direct_assignment+ option, defaulting to
476
+ # {ActiveRecord.direct_assignment}.
477
+ #
478
+ # @return [Symbol] +:allow+ or +:deny+
479
+ # @raise [ArgumentError] when the configured value is not a known mode
480
+ def direct_assignment
481
+ @direct_assignment ||= begin
482
+ mode = integration_options.fetch(:direct_assignment) { ActiveRecord.direct_assignment }
483
+ unless DIRECT_ASSIGNMENT_MODES.include?(mode)
484
+ raise ArgumentError,
485
+ "Invalid direct_assignment: #{mode.inspect} (expected one of #{DIRECT_ASSIGNMENT_MODES.inspect})"
486
+ end
487
+
488
+ mode
489
+ end
490
+ end
491
+
492
+ # @return [Boolean] whether state changes through the model are
493
+ # event-only
494
+ def direct_assignment_denied?
495
+ direct_assignment == :deny
496
+ end
497
+
412
498
  # Check if enum integration should be enabled for this machine
413
499
  def detect_enum_integration
414
500
  return nil unless owner_class.defined_enums.key?(attribute.to_s)
@@ -450,11 +536,64 @@ module StateMachines
450
536
  result
451
537
  end
452
538
 
539
+ # Sets the initial state, remembering whether one was configured
540
+ # explicitly. Without an explicit initial state the attribute's schema
541
+ # default may supply it (see {#initial_state}).
542
+ #
543
+ # @param new_initial_state [Symbol, Proc, nil] the initial state name,
544
+ # a lambda resolving it per record, or nil for none
545
+ # @return [Symbol, Proc, nil] the assigned initial state
546
+ def initial_state=(new_initial_state)
547
+ @explicit_initial_state = !new_initial_state.nil?
548
+ super
549
+ end
550
+
551
+ # Gets the initial state for the given record.
552
+ #
553
+ # An explicit +initial:+ (static or dynamic) always wins. Without one,
554
+ # the attribute's schema default (the database column default, or a
555
+ # default declared through the Attributes API) is used when it names a
556
+ # defined state. The default is read lazily, when a record is built, so
557
+ # defining the machine never requires the table to exist. A default
558
+ # that names no defined state is ignored and the initial state stays
559
+ # nil (the class-load conflicting-default warning reports it).
560
+ #
561
+ # @param object [ActiveRecord::Base] the record being initialized
562
+ # @return [StateMachines::State, nil] the initial state
563
+ def initial_state(object)
564
+ return super if explicit_initial_state?
565
+
566
+ schema_default_state || super
567
+ end
568
+
569
+ # Whether the machine's attribute is not backed by a database column
570
+ # (aliases resolve to their target). Reads the class's memoized
571
+ # columns, so it is cheap enough to call for every loaded record.
572
+ # Returns false while the schema cannot be read.
573
+ #
574
+ # @return [Boolean]
575
+ def transient_attribute?
576
+ name = attribute.to_s
577
+ !owner_class.columns_hash.key?(owner_class.attribute_aliases.fetch(name, name))
578
+ rescue ::ActiveRecord::StatementInvalid, ::ActiveRecord::ConnectionNotEstablished
579
+ false
580
+ end
581
+
582
+ # Whether the machine was given an explicit (non-nil) initial state.
583
+ #
584
+ # @return [Boolean]
585
+ def explicit_initial_state?
586
+ !!@explicit_initial_state
587
+ end
588
+
453
589
  # Warns at most once when the column default conflicts with the
454
590
  # machine's initial state. The conflict is re-evaluated as states are
455
- # defined, so remember when the warning has been issued.
591
+ # defined, so remember when the warning has been issued. No warning is
592
+ # issued when the machine has no explicit initial state and the column
593
+ # default names a defined state: the default then *is* the initial
594
+ # state.
456
595
  def check_conflicting_attribute_default
457
- return if @attribute_default_conflict_warned
596
+ return if @attribute_default_conflict_warned || schema_default_initial_state?
458
597
 
459
598
  initial_state = states.detect(&:initial)
460
599
  conflict = !owner_class_attribute_default.nil? && (
@@ -580,6 +719,31 @@ module StateMachines
580
719
  end
581
720
  end
582
721
 
722
+ # Writes a value to the record. A state write is the machine's own
723
+ # (initialization, a transition persisting its destination, a
724
+ # rollback), so it is authorized for the duration of this single
725
+ # write: callbacks running around it are not (see {StateGuard}).
726
+ #
727
+ # @param object [ActiveRecord::Base] record being written
728
+ # @param attr_sym [Symbol] attribute kind (:state, :event, ...)
729
+ # @param value [Object] the value to write
730
+ # @param ivar [Boolean] whether to write an instance variable
731
+ # @return [Object] the written value
732
+ def write(object, attr_sym, value, ivar = false)
733
+ return super unless attr_sym == :state && !ivar
734
+
735
+ StateGuard.authorize(object, StateGuard.guarded_name(self)) { super }
736
+ end
737
+
738
+ # Runs state events around validation, first refusing to start a
739
+ # transition from a state changed without an event.
740
+ #
741
+ # @param object [ActiveRecord::Base] record being validated
742
+ def around_validation(object, &)
743
+ StateGuard.verify_before_transitions!(object)
744
+ super
745
+ end
746
+
583
747
  # Machine internals (state matching, validations) call read() to get the
584
748
  # current state value and compare it against state.value. The custom
585
749
  # integer type already returns the canonical value when state values are
@@ -611,6 +775,24 @@ module StateMachines
611
775
 
612
776
  private
613
777
 
778
+ # Whether the schema default supplies the initial state: there is no
779
+ # explicit initial state and the default names a defined state.
780
+ #
781
+ # @return [Boolean]
782
+ def schema_default_initial_state?
783
+ !explicit_initial_state? && !schema_default_state.nil?
784
+ end
785
+
786
+ # Finds the named state matching the attribute's schema default.
787
+ #
788
+ # @return [StateMachines::State, nil] the matching state, or nil when
789
+ # there is no default (or no readable schema) or it names no state
790
+ def schema_default_state
791
+ return if owner_class_attribute_default.nil?
792
+
793
+ states.detect { |state| state.name && owner_class_attribute_default_matches?(state) }
794
+ end
795
+
614
796
  # Re-runs the conflicting-default check for states defined after
615
797
  # initialization. Skipped until an initial state exists (the DSL block
616
798
  # evaluates before initial_state= during Machine.new).
@@ -812,11 +994,66 @@ module StateMachines
812
994
  class << self
813
995
  attr_accessor :auto_convert_integer_state_attributes
814
996
 
997
+ # Default +direct_assignment+ mode for machines that do not set one:
998
+ # +:allow+ (default) or +:deny+. Read when a machine is defined.
999
+ #
1000
+ # @return [Symbol]
1001
+ attr_accessor :direct_assignment
1002
+
1003
+ # @return [Array<Symbol>] machine options added by this integration
1004
+ def integration_options
1005
+ [:direct_assignment]
1006
+ end
1007
+
815
1008
  # Classes that inherit from ActiveRecord::Base will automatically use
816
1009
  # the ActiveRecord integration.
817
1010
  def matching_ancestors
818
1011
  [::ActiveRecord::Base]
819
1012
  end
1013
+
1014
+ # Initializes the states of a record loaded from the database for the
1015
+ # machines whose attribute is not a database column (an
1016
+ # +attr_accessor+ or a column-less Attributes API attribute). Loading
1017
+ # skips +initialize+, so without this such records would start with a
1018
+ # blank state. Column-backed machines are left alone: the stored value,
1019
+ # even NULL, is the record's state. Only blank attributes are filled,
1020
+ # static initial states before dynamic ones (which may depend on them),
1021
+ # and before +after_find+/+after_initialize+ callbacks run, so those
1022
+ # callbacks see the initialized state (and may fire events from it).
1023
+ # The writes are the machine's own, so they are authorized (see
1024
+ # {StateGuard}) and run no callbacks.
1025
+ #
1026
+ # @param record [ActiveRecord::Base] the record being loaded
1027
+ # @return [void]
1028
+ def initialize_transient_states(record)
1029
+ machines = record.class.state_machines.values.select(&:transient_attribute?)
1030
+ static, dynamic = machines.partition { |machine| !machine.dynamic_initial_state? }
1031
+ (static + dynamic).each { |machine| machine.initialize_state(record) }
1032
+ end
1033
+
1034
+ # Initializes the states of a new record. A dynamic initial state is
1035
+ # applied even over a column default, like a static one: the column
1036
+ # default is already in the attribute, so core's dynamic pass (which
1037
+ # only fills a blank attribute) would keep it. A state the caller
1038
+ # passed is left in place for {StateGuard} to check. Dynamic states
1039
+ # are evaluated after static ones, which they may depend on; the
1040
+ # caller's +new+ block runs afterwards, so it cannot be overwritten.
1041
+ #
1042
+ # @param record [ActiveRecord::Base] the record being built
1043
+ # @param attributes [Hash] the attributes given to +new+, aliases
1044
+ # resolved, plus the scope's attributes
1045
+ # @return [void]
1046
+ def initialize_new_record_states(record, attributes)
1047
+ machines = record.class.state_machines
1048
+ machines.initialize_states(record, { dynamic: false }, attributes)
1049
+
1050
+ given = attributes.keys.map(&:to_s)
1051
+ machines.each_value do |machine|
1052
+ next unless machine.dynamic_initial_state?
1053
+
1054
+ machine.initialize_state(record, force: !given.include?(StateGuard.guarded_name(machine)))
1055
+ end
1056
+ end
820
1057
  end
821
1058
 
822
1059
  protected
@@ -826,14 +1063,20 @@ module StateMachines
826
1063
  action == :save
827
1064
  end
828
1065
 
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.
1066
+ # Gets the db default for the machine's attribute, resolving attribute
1067
+ # aliases to the underlying column. For integer columns the raw
1068
+ # pre-type-registration default is returned so that
1069
+ # check_conflicting_attribute_default can compare integers to integers.
1070
+ # Returns nil while the schema cannot be read (no connection, no table).
1071
+ #
1072
+ # @return [Object, nil] the default value
832
1073
  def owner_class_attribute_default
833
1074
  return @raw_integer_column_default if defined?(@raw_integer_column_default)
834
1075
  return unless owner_class.connected? && owner_class.table_exists?
835
1076
 
836
- owner_class.column_defaults[attribute.to_s]
1077
+ owner_class.column_defaults[owner_class.attribute_aliases.fetch(attribute.to_s, attribute.to_s)]
1078
+ rescue ::ActiveRecord::StatementInvalid, ::ActiveRecord::ConnectionNotEstablished
1079
+ nil
837
1080
  end
838
1081
 
839
1082
  # Checks whether the given state matches the column default. When the
@@ -855,14 +1098,23 @@ module StateMachines
855
1098
  def define_state_initializer
856
1099
  define_helper :instance, <<-END_EVAL, __FILE__, __LINE__ + 1
857
1100
  def initialize(attributes = nil, *)
1101
+ StateMachines::Integrations::ActiveRecord::StateGuard.begin_construction(self)
858
1102
  super(attributes) do |*args|
859
1103
  attributes = (attributes || {}).transform_keys { |key| self.class.attribute_aliases[key.to_s] || key }
860
1104
  scoped_attributes = attributes.merge(self.class.scope_attributes)
861
1105
 
862
- self.class.state_machines.initialize_states(self, {}, scoped_attributes)
1106
+ StateMachines::Integrations::ActiveRecord.initialize_new_record_states(self, scoped_attributes)
1107
+ StateMachines::Integrations::ActiveRecord::StateGuard.finish_construction(self)
863
1108
  yield(*args) if block_given?
864
1109
  end
865
1110
  end
1111
+
1112
+ def init_with_attributes(attributes, new_record = false)
1113
+ super do |record|
1114
+ StateMachines::Integrations::ActiveRecord.initialize_transient_states(record)
1115
+ yield record if block_given?
1116
+ end
1117
+ end
866
1118
  END_EVAL
867
1119
  end
868
1120
 
@@ -890,6 +1142,7 @@ module StateMachines
890
1142
 
891
1143
  # Runs state events around the machine's :save action
892
1144
  def around_save(object, &)
1145
+ StateGuard.verify_before_transitions!(object)
893
1146
  # Pass fiber: false to avoid deadlocks with ActiveRecord's LoadInterlockAwareMonitor
894
1147
  object.class.state_machines.transitions(object, action, fiber: false).perform(&)
895
1148
  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.303.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,10 @@ 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
138
+ - lib/state_machines/integrations/active_record/force_state.rb
123
139
  - lib/state_machines/integrations/active_record/locale.rb
140
+ - lib/state_machines/integrations/active_record/state_guard.rb
124
141
  - lib/state_machines/integrations/active_record/type/integer.rb
125
142
  - lib/state_machines/integrations/active_record/version.rb
126
143
  homepage: https://github.com/state-machines/state_machines-activerecord/
@@ -135,14 +152,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
135
152
  requirements:
136
153
  - - ">="
137
154
  - !ruby/object:Gem::Version
138
- version: '3.2'
155
+ version: '4.0'
139
156
  required_rubygems_version: !ruby/object:Gem::Requirement
140
157
  requirements:
141
158
  - - ">="
142
159
  - !ruby/object:Gem::Version
143
160
  version: '0'
144
161
  requirements: []
145
- rubygems_version: 4.0.10
162
+ rubygems_version: 4.0.20
146
163
  specification_version: 4
147
164
  summary: State machines Active Record Integration
148
165
  test_files: []