4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
# File 'lib/nxt_state_machine/integrations/active_record.rb', line 4
def state_machine(name = :default, state_attr: :state, target: nil, lock_transitions: true, &config)
machine = super(
name,
state_attr: state_attr,
target: target,
lock_transitions: lock_transitions,
&config
)
machine.get_state_with do |target|
if target
if target.send(state_attr).nil? && target.new_record?
target.assign_attributes(state_attr => machine.initial_state.to_s)
end
current_state = target.send(state_attr)
current_state&.to_sym
end
end
machine.set_state_with do |target, transition|
set_state(machine, target, transition, state_attr, :save)
end
machine.set_state_with! do |target, transition|
set_state(machine, target, transition, state_attr, :save!)
end
machine.define_singleton_method :add_state_methods_to_model do |model_class|
model_class.class_eval do
machine.states.keys.each do |state_name|
define_method "#{state_name}?" do
send(machine.options.fetch(:state_attr)) == state_name
end
end
end
end
machine
end
|