state_machines-activerecord 0.103.0 → 0.300.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +242 -3
- data/lib/state_machines/integrations/active_record/errors.rb +83 -0
- data/lib/state_machines/integrations/active_record/state_guard.rb +449 -0
- data/lib/state_machines/integrations/active_record/type/integer.rb +76 -15
- data/lib/state_machines/integrations/active_record/version.rb +1 -1
- data/lib/state_machines/integrations/active_record.rb +371 -27
- metadata +13 -11
|
@@ -0,0 +1,449 @@
|
|
|
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.
|
|
9
|
+
#
|
|
10
|
+
# Every write of a machine's attribute through the model (setter, mass
|
|
11
|
+
# assignment, attribute alias, +record[:attr] =+, +write_attribute+) is
|
|
12
|
+
# checked before the value changes:
|
|
13
|
+
#
|
|
14
|
+
# * writes performed by the machine itself (initialization, a
|
|
15
|
+
# transition persisting its destination, a rollback) are authorized
|
|
16
|
+
# for the duration of that single write only, so callbacks running
|
|
17
|
+
# around a transition cannot overwrite the state;
|
|
18
|
+
# * assigning the value the record already holds (compared through the
|
|
19
|
+
# attribute's type, so +:parked+, +'parked'+ and an integer-backed
|
|
20
|
+
# +0+ are the same) is allowed and runs nothing;
|
|
21
|
+
# * anything else raises {StateMachines::DirectStateAssignment}.
|
|
22
|
+
#
|
|
23
|
+
# While a record is being built, assigned states are collected and,
|
|
24
|
+
# once the machines have initialized, must equal the initial state.
|
|
25
|
+
#
|
|
26
|
+
# As a backstop, saving a record whose state attribute changed without
|
|
27
|
+
# an authorized write (e.g. an in-place mutation or a write straight to
|
|
28
|
+
# the attribute set) raises the same error.
|
|
29
|
+
#
|
|
30
|
+
# Raw persistence (+update_column(s)+, +update_all+, +insert_all+,
|
|
31
|
+
# SQL) and database hydration / +reload+ never go through attribute
|
|
32
|
+
# writers and are left alone.
|
|
33
|
+
module StateGuard
|
|
34
|
+
# Names of attributes the machine is currently writing
|
|
35
|
+
AUTHORIZED_WRITES = :@_state_machines_authorized_writes
|
|
36
|
+
|
|
37
|
+
# Attribute name => last state value written by the machine
|
|
38
|
+
AUTHORIZED_STATES = :@_state_machines_authorized_states
|
|
39
|
+
|
|
40
|
+
# Attribute names assigned while the record is being built
|
|
41
|
+
CONSTRUCTION_WRITES = :@_state_machines_construction_writes
|
|
42
|
+
|
|
43
|
+
# Instance methods mixed into every model owning a state machine.
|
|
44
|
+
module RecordMethods
|
|
45
|
+
# Updates an attribute, refusing a direct change of a state machine
|
|
46
|
+
# attribute.
|
|
47
|
+
#
|
|
48
|
+
# @param attr_name [String, Symbol] attribute (or alias) name
|
|
49
|
+
# @param value [Object] the new value
|
|
50
|
+
# @raise [StateMachines::DirectStateAssignment]
|
|
51
|
+
def write_attribute(attr_name, value)
|
|
52
|
+
name = attr_name.to_s
|
|
53
|
+
StateGuard.check_write!(self, self.class.attribute_aliases[name] || name, value)
|
|
54
|
+
super
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# @api private
|
|
58
|
+
# @see #write_attribute
|
|
59
|
+
def _write_attribute(attr_name, value)
|
|
60
|
+
StateGuard.check_write!(self, attr_name.to_s, value)
|
|
61
|
+
super
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Converts the record to another class, preserving its state.
|
|
65
|
+
#
|
|
66
|
+
# No transition callbacks run, and a state changed without an event
|
|
67
|
+
# stays unauthorized on the new instance.
|
|
68
|
+
#
|
|
69
|
+
# @param klass [Class] the class to convert to
|
|
70
|
+
# @return [ActiveRecord::Base] the converted record
|
|
71
|
+
# @raise [StateMachines::PendingStateEvent] while an event attribute
|
|
72
|
+
# or a transition prepared by validation is queued
|
|
73
|
+
def becomes(klass)
|
|
74
|
+
StateGuard.ensure_no_queued_work!(self)
|
|
75
|
+
super.tap { |became| StateGuard.copy_authorizations(self, became) }
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# Duplicates the record with its state. Dirty tracking restarts on
|
|
79
|
+
# the copy, so the states the original holds legitimately are
|
|
80
|
+
# authorized on it; a state changed without an event is not.
|
|
81
|
+
#
|
|
82
|
+
# @param other [ActiveRecord::Base] the original record
|
|
83
|
+
# @return [void]
|
|
84
|
+
def initialize_dup(other)
|
|
85
|
+
legitimate = StateGuard.legitimate_states(other)
|
|
86
|
+
super
|
|
87
|
+
remove_instance_variable(AUTHORIZED_WRITES) if instance_variable_defined?(AUTHORIZED_WRITES)
|
|
88
|
+
instance_variable_set(AUTHORIZED_STATES, legitimate)
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# Reloads the record, forgetting state authorizations: the reloaded
|
|
92
|
+
# attributes are the database's.
|
|
93
|
+
#
|
|
94
|
+
# @return [ActiveRecord::Base] the reloaded record
|
|
95
|
+
def reload(*)
|
|
96
|
+
super.tap { StateGuard.forget(self) }
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# Forgets state authorizations once changes are persisted.
|
|
100
|
+
#
|
|
101
|
+
# @return [void]
|
|
102
|
+
def changes_applied
|
|
103
|
+
super
|
|
104
|
+
StateGuard.forget(self)
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# Forgets state authorizations along with the dirty tracking.
|
|
108
|
+
#
|
|
109
|
+
# @return [void]
|
|
110
|
+
def clear_changes_information
|
|
111
|
+
super
|
|
112
|
+
StateGuard.forget(self)
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
private
|
|
116
|
+
|
|
117
|
+
# @see #write_attribute
|
|
118
|
+
def attribute=(attr_name, value)
|
|
119
|
+
StateGuard.check_write!(self, attr_name.to_s, value)
|
|
120
|
+
super
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
# Saves, first refusing state changes made without an event.
|
|
124
|
+
def create_or_update(...)
|
|
125
|
+
StateGuard.verify_persistable!(self)
|
|
126
|
+
super
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
# Checks again once +before_save+ callbacks have run.
|
|
130
|
+
def _create_record(...)
|
|
131
|
+
StateGuard.verify_persistable!(self)
|
|
132
|
+
super
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
# Checks again once +before_save+ callbacks have run.
|
|
136
|
+
def _update_record(...)
|
|
137
|
+
StateGuard.verify_persistable!(self)
|
|
138
|
+
super
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
# Restoring an attribute to its database value is a revert, not a
|
|
142
|
+
# state change, so the write is authorized.
|
|
143
|
+
def restore_attribute!(attr_name)
|
|
144
|
+
StateGuard.authorize(self, attr_name.to_s) { super }
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
# Forgets the authorization of an attribute whose change is cleared
|
|
148
|
+
# (e.g. by +update_columns+).
|
|
149
|
+
def clear_attribute_change(attr_name)
|
|
150
|
+
super
|
|
151
|
+
StateGuard.forget(self, attr_name.to_s)
|
|
152
|
+
end
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
# Guards the writers of machine attributes: the attribute itself,
|
|
156
|
+
# the column it aliases and every alias of that column, whether an
|
|
157
|
+
# ActiveRecord attribute or not (e.g. +attr_accessor+).
|
|
158
|
+
class WriterGuard < Module
|
|
159
|
+
# @return [Set<String>] the attributes whose writers are guarded,
|
|
160
|
+
# aliases resolved
|
|
161
|
+
attr_reader :targets
|
|
162
|
+
|
|
163
|
+
def initialize
|
|
164
|
+
super
|
|
165
|
+
@targets = Set.new
|
|
166
|
+
@writers = Set.new
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
# Guards the writer of +name+.
|
|
170
|
+
#
|
|
171
|
+
# @param name [String] an attribute or alias name
|
|
172
|
+
# @return [void]
|
|
173
|
+
def guard(name)
|
|
174
|
+
return unless @writers.add?(name)
|
|
175
|
+
|
|
176
|
+
define_method(:"#{name}=") do |value|
|
|
177
|
+
StateGuard.check_write!(self, self.class.attribute_aliases[name] || name, value)
|
|
178
|
+
super(value)
|
|
179
|
+
end
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
# Guards writers of aliases declared after the machine.
|
|
184
|
+
module AliasGuard
|
|
185
|
+
# @see ActiveRecord::AttributeMethods::ClassMethods#alias_attribute
|
|
186
|
+
def alias_attribute(new_name, old_name)
|
|
187
|
+
super.tap do
|
|
188
|
+
guard = StateGuard.writer_guard(self)
|
|
189
|
+
target = attribute_aliases.fetch(old_name.to_s, old_name.to_s)
|
|
190
|
+
guard.guard(new_name.to_s) if guard&.targets&.include?(target)
|
|
191
|
+
end
|
|
192
|
+
end
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
class << self
|
|
196
|
+
# Installs the guard on a model class for a machine.
|
|
197
|
+
#
|
|
198
|
+
# @param klass [Class] the model class
|
|
199
|
+
# @param attribute [Symbol] the machine's attribute
|
|
200
|
+
# @return [void]
|
|
201
|
+
def install(klass, attribute)
|
|
202
|
+
klass.include(RecordMethods) unless klass < RecordMethods
|
|
203
|
+
klass.singleton_class.prepend(AliasGuard) unless klass.singleton_class < AliasGuard
|
|
204
|
+
guard = writer_guard(klass) || WriterGuard.new.tap { |mod| klass.prepend(mod) }
|
|
205
|
+
|
|
206
|
+
name = attribute.to_s
|
|
207
|
+
target = klass.attribute_aliases.fetch(name, name)
|
|
208
|
+
guard.targets << target
|
|
209
|
+
[name, target, *klass.attribute_aliases.select { |_, aliased| aliased == target }.keys]
|
|
210
|
+
.each { |writer| guard.guard(writer) }
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
# @param klass [Class] a model class
|
|
214
|
+
# @return [WriterGuard, nil] the writer guard of the class
|
|
215
|
+
def writer_guard(klass)
|
|
216
|
+
klass.ancestors.find { |mod| mod.is_a?(WriterGuard) }
|
|
217
|
+
end
|
|
218
|
+
|
|
219
|
+
# Checks a write of attribute +name+ before it happens.
|
|
220
|
+
#
|
|
221
|
+
# @param record [ActiveRecord::Base] the record being written
|
|
222
|
+
# @param name [String] the attribute name, aliases resolved
|
|
223
|
+
# @param value [Object] the value being written
|
|
224
|
+
# @return [void]
|
|
225
|
+
# @raise [StateMachines::DirectStateAssignment] when the write
|
|
226
|
+
# changes the state of a machine without authorization
|
|
227
|
+
def check_write!(record, name, value)
|
|
228
|
+
machine = machine_for(record, name)
|
|
229
|
+
return unless machine
|
|
230
|
+
return if record.instance_variable_get(AUTHORIZED_WRITES)&.include?(name)
|
|
231
|
+
|
|
232
|
+
if (writes = record.instance_variable_get(CONSTRUCTION_WRITES))
|
|
233
|
+
writes << name
|
|
234
|
+
return
|
|
235
|
+
end
|
|
236
|
+
|
|
237
|
+
current = current_value(record, machine)
|
|
238
|
+
return if same_state?(record, machine, current, value)
|
|
239
|
+
|
|
240
|
+
raise DirectStateAssignment.new(record, machine: machine, from: current, to: value)
|
|
241
|
+
end
|
|
242
|
+
|
|
243
|
+
# Authorizes writes of attribute +name+ for the duration of the
|
|
244
|
+
# block, then remembers the written value as legitimate.
|
|
245
|
+
#
|
|
246
|
+
# @param record [ActiveRecord::Base] the record being written
|
|
247
|
+
# @param name [String] the attribute name, aliases resolved
|
|
248
|
+
# @return [Object] the block's result
|
|
249
|
+
def authorize(record, name)
|
|
250
|
+
writes = record.instance_variable_get(AUTHORIZED_WRITES) ||
|
|
251
|
+
record.instance_variable_set(AUTHORIZED_WRITES, Set.new)
|
|
252
|
+
added = writes.add?(name)
|
|
253
|
+
result = yield
|
|
254
|
+
machine = machine_for(record, name)
|
|
255
|
+
remember(record, name, current_value(record, machine)) if machine
|
|
256
|
+
result
|
|
257
|
+
ensure
|
|
258
|
+
writes.delete(name) if added
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
# Starts collecting state assignments made while building a record.
|
|
262
|
+
#
|
|
263
|
+
# @param record [ActiveRecord::Base] the record being built
|
|
264
|
+
# @return [void]
|
|
265
|
+
def begin_construction(record)
|
|
266
|
+
record.instance_variable_set(CONSTRUCTION_WRITES, Set.new)
|
|
267
|
+
end
|
|
268
|
+
|
|
269
|
+
# Stops collecting state assignments and checks that each assigned
|
|
270
|
+
# state equals the machine's initial state for the record (static,
|
|
271
|
+
# dynamic or schema-default).
|
|
272
|
+
#
|
|
273
|
+
# @param record [ActiveRecord::Base] the record being built
|
|
274
|
+
# @return [void]
|
|
275
|
+
# @raise [StateMachines::DirectStateAssignment] when a state other
|
|
276
|
+
# than the initial one was assigned
|
|
277
|
+
def finish_construction(record)
|
|
278
|
+
writes = record.instance_variable_get(CONSTRUCTION_WRITES)
|
|
279
|
+
record.instance_variable_set(CONSTRUCTION_WRITES, nil)
|
|
280
|
+
return if writes.nil? || writes.empty?
|
|
281
|
+
|
|
282
|
+
# Machines sharing an attribute (e.g. a public and a private
|
|
283
|
+
# machine) share its initial state, set on one of them
|
|
284
|
+
machines = record.class.state_machines.values.group_by { |machine| guarded_name(machine) }
|
|
285
|
+
machines.slice(*writes).each do |name, siblings|
|
|
286
|
+
machine = siblings.find { |sibling| sibling.initial_state(record) } || siblings.first
|
|
287
|
+
current = current_value(record, machine)
|
|
288
|
+
expected = machine.initial_state(record)&.value
|
|
289
|
+
next remember(record, name, current) if same_state?(record, machine, expected, current)
|
|
290
|
+
|
|
291
|
+
raise DirectStateAssignment.new(record, machine: machine, from: expected, to: current)
|
|
292
|
+
end
|
|
293
|
+
end
|
|
294
|
+
|
|
295
|
+
# Refuses to persist a state attribute that changed without an
|
|
296
|
+
# authorized write.
|
|
297
|
+
#
|
|
298
|
+
# @param record [ActiveRecord::Base] the record being saved
|
|
299
|
+
# @return [void]
|
|
300
|
+
# @raise [StateMachines::DirectStateAssignment]
|
|
301
|
+
def verify_persistable!(record)
|
|
302
|
+
each_persisted_state(record) do |machine, name, current, legitimate|
|
|
303
|
+
next if legitimate
|
|
304
|
+
|
|
305
|
+
from = record.attribute_in_database(name)
|
|
306
|
+
raise DirectStateAssignment.new(record, machine: machine, from: from, to: current)
|
|
307
|
+
end
|
|
308
|
+
end
|
|
309
|
+
|
|
310
|
+
# The persisted state attributes whose current value the record
|
|
311
|
+
# holds legitimately: unchanged, or last written by the machine.
|
|
312
|
+
#
|
|
313
|
+
# @param record [ActiveRecord::Base]
|
|
314
|
+
# @return [Hash{String => Object}] attribute name => current value
|
|
315
|
+
def legitimate_states(record)
|
|
316
|
+
states = {}
|
|
317
|
+
each_persisted_state(record) { |_machine, name, current, legitimate| states[name] = current if legitimate }
|
|
318
|
+
states
|
|
319
|
+
end
|
|
320
|
+
|
|
321
|
+
# Like {verify_persistable!}, but only while some machine has an
|
|
322
|
+
# event queued, so no transition starts from an unauthorized state.
|
|
323
|
+
#
|
|
324
|
+
# @param record [ActiveRecord::Base] the record about to transition
|
|
325
|
+
# @return [void]
|
|
326
|
+
def verify_before_transitions!(record)
|
|
327
|
+
verify_persistable!(record) if queued_work(record)
|
|
328
|
+
end
|
|
329
|
+
|
|
330
|
+
# @param record [ActiveRecord::Base] the record being converted
|
|
331
|
+
# @return [void]
|
|
332
|
+
# @raise [StateMachines::PendingStateEvent] when an event attribute
|
|
333
|
+
# or a prepared transition is queued
|
|
334
|
+
def ensure_no_queued_work!(record)
|
|
335
|
+
machine, event = queued_work(record)
|
|
336
|
+
raise PendingStateEvent.new(record, machine, event) if machine
|
|
337
|
+
end
|
|
338
|
+
|
|
339
|
+
# Gives +target+ the same state authorizations as +source+.
|
|
340
|
+
#
|
|
341
|
+
# @return [void]
|
|
342
|
+
def copy_authorizations(source, target)
|
|
343
|
+
target.instance_variable_set(AUTHORIZED_STATES, source.instance_variable_get(AUTHORIZED_STATES)&.dup)
|
|
344
|
+
end
|
|
345
|
+
|
|
346
|
+
# Forgets the remembered state of one or every attribute.
|
|
347
|
+
#
|
|
348
|
+
# @param record [ActiveRecord::Base]
|
|
349
|
+
# @param name [String, nil] the attribute, or nil for all
|
|
350
|
+
# @return [void]
|
|
351
|
+
def forget(record, name = nil)
|
|
352
|
+
authorized = record.instance_variable_get(AUTHORIZED_STATES)
|
|
353
|
+
return unless authorized
|
|
354
|
+
|
|
355
|
+
name ? authorized.delete(name) : authorized.clear
|
|
356
|
+
end
|
|
357
|
+
|
|
358
|
+
# The attribute a machine writes, aliases resolved.
|
|
359
|
+
#
|
|
360
|
+
# @param machine [StateMachines::Machine]
|
|
361
|
+
# @return [String]
|
|
362
|
+
def guarded_name(machine)
|
|
363
|
+
name = machine.attribute.to_s
|
|
364
|
+
machine.owner_class.attribute_aliases.fetch(name, name)
|
|
365
|
+
end
|
|
366
|
+
|
|
367
|
+
private
|
|
368
|
+
|
|
369
|
+
# Yields each database-backed state attribute of the record with
|
|
370
|
+
# its current value and whether the record holds it legitimately.
|
|
371
|
+
#
|
|
372
|
+
# @yieldparam machine [StateMachines::Machine]
|
|
373
|
+
# @yieldparam name [String] the attribute name, aliases resolved
|
|
374
|
+
# @yieldparam current [Object] the current value
|
|
375
|
+
# @yieldparam legitimate [Boolean] unchanged, or last written by
|
|
376
|
+
# the machine
|
|
377
|
+
# @return [void]
|
|
378
|
+
def each_persisted_state(record)
|
|
379
|
+
authorized = record.instance_variable_get(AUTHORIZED_STATES)
|
|
380
|
+
seen = Set.new
|
|
381
|
+
|
|
382
|
+
record.class.state_machines.each_value do |machine|
|
|
383
|
+
name = guarded_name(machine)
|
|
384
|
+
next unless seen.add?(name) && record._has_attribute?(name) && !machine.transient_attribute?
|
|
385
|
+
|
|
386
|
+
current = record._read_attribute(name)
|
|
387
|
+
legitimate = !record.attribute_changed?(name) ||
|
|
388
|
+
(authorized&.key?(name) && same_state?(record, machine, authorized[name], current))
|
|
389
|
+
yield machine, name, current, legitimate
|
|
390
|
+
end
|
|
391
|
+
end
|
|
392
|
+
|
|
393
|
+
# @return [StateMachines::Machine, nil] the first machine writing
|
|
394
|
+
# attribute +name+
|
|
395
|
+
def machine_for(record, name)
|
|
396
|
+
record.class.state_machines.each_value.find { |machine| guarded_name(machine) == name }
|
|
397
|
+
end
|
|
398
|
+
|
|
399
|
+
# @return [Array(StateMachines::Machine, Object), nil] the first
|
|
400
|
+
# machine with queued work and its event
|
|
401
|
+
def queued_work(record)
|
|
402
|
+
record.class.state_machines.each_value do |machine|
|
|
403
|
+
next unless machine.action
|
|
404
|
+
|
|
405
|
+
event = machine.read(record, :event)
|
|
406
|
+
event ||= machine.read(record, :event_transition, true)&.event
|
|
407
|
+
return [machine, event] if event
|
|
408
|
+
end
|
|
409
|
+
nil
|
|
410
|
+
end
|
|
411
|
+
|
|
412
|
+
# @return [Object] the current value of the machine's attribute
|
|
413
|
+
def current_value(record, machine)
|
|
414
|
+
name = guarded_name(machine)
|
|
415
|
+
record._has_attribute?(name) ? record._read_attribute(name) : record.public_send(machine.attribute)
|
|
416
|
+
end
|
|
417
|
+
|
|
418
|
+
# Whether two values denote the same stored state, compared through
|
|
419
|
+
# the attribute's type (symbols and strings, integer-backed states,
|
|
420
|
+
# enums).
|
|
421
|
+
#
|
|
422
|
+
# @return [Boolean]
|
|
423
|
+
def same_state?(record, machine, left, right)
|
|
424
|
+
canonical(record, machine, left) == canonical(record, machine, right)
|
|
425
|
+
end
|
|
426
|
+
|
|
427
|
+
# @return [Object] the value as the attribute would store it
|
|
428
|
+
def canonical(record, machine, value)
|
|
429
|
+
name = guarded_name(machine)
|
|
430
|
+
if record._has_attribute?(name)
|
|
431
|
+
record.class.type_for_attribute(name).cast(value)
|
|
432
|
+
else
|
|
433
|
+
value.is_a?(Symbol) ? value.to_s : value
|
|
434
|
+
end
|
|
435
|
+
end
|
|
436
|
+
|
|
437
|
+
# Remembers +value+ as the legitimate state of attribute +name+.
|
|
438
|
+
#
|
|
439
|
+
# @return [void]
|
|
440
|
+
def remember(record, name, value)
|
|
441
|
+
authorized = record.instance_variable_get(AUTHORIZED_STATES) ||
|
|
442
|
+
record.instance_variable_set(AUTHORIZED_STATES, {})
|
|
443
|
+
authorized[name] = value
|
|
444
|
+
end
|
|
445
|
+
end
|
|
446
|
+
end
|
|
447
|
+
end
|
|
448
|
+
end
|
|
449
|
+
end
|
|
@@ -9,52 +9,113 @@ module StateMachines
|
|
|
9
9
|
# States without explicit integer values are mapped by their index position
|
|
10
10
|
# in the states collection (0, 1, 2, …). States with an explicit integer
|
|
11
11
|
# value (e.g. state :pending, value: 2) use that value directly.
|
|
12
|
+
#
|
|
13
|
+
# When *every* named state has an explicit integer value, the column already
|
|
14
|
+
# stores the canonical state values and no name<->integer conversion is
|
|
15
|
+
# needed. In that case the type delegates to the column's original integer
|
|
16
|
+
# type, preserving the classic raw-integer behavior
|
|
17
|
+
# (e.g. record.status # => 1, record.status_name # => :approved).
|
|
12
18
|
class Integer < ::ActiveRecord::Type::Value
|
|
13
|
-
|
|
19
|
+
# The column's original attribute type, exposed so re-registration
|
|
20
|
+
# (e.g. for STI subclasses) can reuse it instead of wrapping this type.
|
|
21
|
+
#
|
|
22
|
+
# @return [ActiveModel::Type::Value]
|
|
23
|
+
attr_reader :raw_type
|
|
24
|
+
|
|
25
|
+
# @param states [StateMachines::StateCollection] live collection of the
|
|
26
|
+
# machine's states; held by reference because states are defined after
|
|
27
|
+
# the type is registered
|
|
28
|
+
# @param raw_type [ActiveModel::Type::Value, nil] the column's original
|
|
29
|
+
# attribute type, used verbatim in passthrough mode so adapter-specific
|
|
30
|
+
# integer behavior (limits, range checks) is preserved
|
|
31
|
+
def initialize(states, raw_type: nil)
|
|
14
32
|
@states = states
|
|
33
|
+
@raw_type = raw_type || ::ActiveModel::Type::Integer.new
|
|
15
34
|
super()
|
|
16
35
|
end
|
|
17
36
|
|
|
18
|
-
# integer from
|
|
37
|
+
# Converts an integer from the database to a state name string.
|
|
38
|
+
#
|
|
39
|
+
# @param value [Integer, String, nil] raw database value
|
|
40
|
+
# @return [String, Integer, nil] state name, or the original type's value
|
|
41
|
+
# in passthrough mode, or the raw value when no state matches
|
|
19
42
|
def deserialize(value)
|
|
43
|
+
states = named_states
|
|
44
|
+
return @raw_type.deserialize(value) if passthrough?(states)
|
|
20
45
|
return nil if value.nil?
|
|
46
|
+
|
|
21
47
|
int_val = value.to_i
|
|
22
|
-
state =
|
|
48
|
+
state = states.detect { |s| state_integer(s, states) == int_val }
|
|
23
49
|
state ? state.name.to_s : value
|
|
24
50
|
end
|
|
25
51
|
|
|
26
|
-
#
|
|
52
|
+
# Converts an assigned value (symbol, string, or integer) to the in-memory
|
|
53
|
+
# state name string.
|
|
54
|
+
#
|
|
55
|
+
# @param value [Symbol, String, Integer, nil] assigned value
|
|
56
|
+
# @return [String, Integer, nil] state name, or the original type's cast
|
|
57
|
+
# in passthrough mode
|
|
27
58
|
def cast(value)
|
|
59
|
+
states = named_states
|
|
60
|
+
return @raw_type.cast(value) if passthrough?(states)
|
|
28
61
|
return nil if value.nil?
|
|
29
|
-
|
|
30
|
-
state
|
|
62
|
+
|
|
63
|
+
state = states.detect { |s| s.name.to_s == value.to_s }
|
|
64
|
+
state ||= states.detect { |s| state_integer(s, states) == value.to_i } if value.respond_to?(:to_i)
|
|
31
65
|
state ? state.name.to_s : value.to_s
|
|
32
66
|
end
|
|
33
67
|
|
|
34
|
-
# state name string
|
|
68
|
+
# Converts a state name string to its integer for the database write.
|
|
69
|
+
#
|
|
70
|
+
# @param value [String, Symbol, Integer, nil] in-memory value
|
|
71
|
+
# @return [Integer, nil] integer to store
|
|
35
72
|
def serialize(value)
|
|
73
|
+
states = named_states
|
|
74
|
+
return @raw_type.serialize(value) if passthrough?(states)
|
|
36
75
|
return nil if value.nil?
|
|
37
|
-
|
|
38
|
-
state
|
|
76
|
+
|
|
77
|
+
state = states.detect { |s| s.name.to_s == value.to_s }
|
|
78
|
+
state ? state_integer(state, states) : value
|
|
39
79
|
end
|
|
40
80
|
|
|
81
|
+
# @return [Symbol] the ActiveModel type identifier
|
|
41
82
|
def type
|
|
42
83
|
:integer
|
|
43
84
|
end
|
|
44
85
|
|
|
45
86
|
private
|
|
46
87
|
|
|
47
|
-
# All non-nil states in definition order
|
|
88
|
+
# All non-nil states in definition order, not memoized because states are
|
|
48
89
|
# added to the collection after the type is instantiated.
|
|
90
|
+
#
|
|
91
|
+
# @return [Array<StateMachines::State>]
|
|
49
92
|
def named_states
|
|
50
93
|
@states.reject { |s| s.name.nil? }
|
|
51
94
|
end
|
|
52
95
|
|
|
53
|
-
#
|
|
54
|
-
#
|
|
55
|
-
#
|
|
56
|
-
|
|
57
|
-
|
|
96
|
+
# Whether the machine was defined for raw integer storage, in which case
|
|
97
|
+
# conversion would change documented behavior. True when every named state
|
|
98
|
+
# declares an explicit integer value. Evaluated lazily on every call
|
|
99
|
+
# because states (and their values) are defined after the type is
|
|
100
|
+
# registered. Uses value(false) so dynamic (Proc) state values are never
|
|
101
|
+
# evaluated for this metadata decision.
|
|
102
|
+
#
|
|
103
|
+
# @param states [Array<StateMachines::State>] pre-computed named states
|
|
104
|
+
# @return [Boolean]
|
|
105
|
+
def passthrough?(states)
|
|
106
|
+
states.any? && states.all? { |s| s.value(false).is_a?(::Integer) }
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# The integer to use for storage: the explicit state value if set
|
|
110
|
+
# (e.g. state :pending, value: 2), otherwise the index position among
|
|
111
|
+
# named states.
|
|
112
|
+
#
|
|
113
|
+
# @param state [StateMachines::State]
|
|
114
|
+
# @param states [Array<StateMachines::State>] pre-computed named states
|
|
115
|
+
# @return [Integer]
|
|
116
|
+
def state_integer(state, states)
|
|
117
|
+
value = state.value(false)
|
|
118
|
+
value.is_a?(::Integer) ? value : states.index(state)
|
|
58
119
|
end
|
|
59
120
|
end
|
|
60
121
|
end
|