Skip to content

Commit 751dd46

Browse files
committed
Define state constants
1 parent a45a827 commit 751dd46

File tree

3 files changed

+37
-2
lines changed

3 files changed

+37
-2
lines changed

README.md

+10
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,16 @@ Machine.successors
366366
}
367367
```
368368

369+
## Class constants
370+
Each machine's state will turn into a constant:
371+
```ruby
372+
Machine.state(:some_state, initial: true)
373+
Machine.state(:another_state)
374+
375+
Machine::SOME_STATE #=> "some_state"
376+
Machine::ANOTHER_STATE # => "another_state"
377+
```
378+
369379
## Instance methods
370380

371381
#### `Machine#current_state`

lib/statesman/machine.rb

+12
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ def state(name, options = { initial: false })
3939
validate_initial_state(name)
4040
@initial_state = name
4141
end
42+
define_state_constant(name)
43+
4244
states << name
4345
end
4446

@@ -163,6 +165,16 @@ def validate_from_and_to_state(from, to)
163165

164166
private
165167

168+
def define_state_constant(state_name)
169+
constant_name = state_name.upcase
170+
171+
if const_defined?(constant_name)
172+
warn "Name conflict: '#{self.class.name}::#{constant_name}' is already defined"
173+
else
174+
const_set(constant_name, state_name)
175+
end
176+
end
177+
166178
def add_callback(callback_type: nil, callback_class: nil,
167179
from: nil, to: nil, &block)
168180
validate_callback_type_and_class(callback_type, callback_class)

spec/statesman/machine_spec.rb

+15-2
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,14 @@
1313

1414
specify { expect(machine.states).to eq(%w[x y]) }
1515

16+
specify { expect(machine::X).to eq "x" }
17+
18+
specify { expect(machine::Y).to eq "y" }
19+
1620
context "initial" do
17-
before { machine.state(:x, initial: true) }
21+
before { machine.state(:z, initial: true) }
1822

19-
specify { expect(machine.initial_state).to eq("x") }
23+
specify { expect(machine.initial_state).to eq("z") }
2024

2125
context "when an initial state is already defined" do
2226
it "raises an error" do
@@ -25,6 +29,15 @@
2529
end
2630
end
2731
end
32+
33+
context "when state name constant is already defined" do
34+
it "warns about name conflict" do
35+
machine.const_set(:SOME_CONST, "some const")
36+
warning_message = "Name conflict: 'Class::SOME_CONST' is already defined\n"
37+
38+
expect { machine.state(:some_const) }.to output(warning_message).to_stderr
39+
end
40+
end
2841
end
2942

3043
describe ".remove_state" do

0 commit comments

Comments
 (0)