Skip to content

Commit

Permalink
Define state constants
Browse files Browse the repository at this point in the history
  • Loading branch information
stephannv committed Sep 26, 2023
1 parent a45a827 commit 751dd46
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,16 @@ Machine.successors
}
```

## Class constants
Each machine's state will turn into a constant:
```ruby
Machine.state(:some_state, initial: true)
Machine.state(:another_state)

Machine::SOME_STATE #=> "some_state"
Machine::ANOTHER_STATE # => "another_state"
```

## Instance methods

#### `Machine#current_state`
Expand Down
12 changes: 12 additions & 0 deletions lib/statesman/machine.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ def state(name, options = { initial: false })
validate_initial_state(name)
@initial_state = name
end
define_state_constant(name)

states << name
end

Expand Down Expand Up @@ -163,6 +165,16 @@ def validate_from_and_to_state(from, to)

private

def define_state_constant(state_name)
constant_name = state_name.upcase

if const_defined?(constant_name)
warn "Name conflict: '#{self.class.name}::#{constant_name}' is already defined"
else
const_set(constant_name, state_name)
end
end

def add_callback(callback_type: nil, callback_class: nil,
from: nil, to: nil, &block)
validate_callback_type_and_class(callback_type, callback_class)
Expand Down
17 changes: 15 additions & 2 deletions spec/statesman/machine_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,14 @@

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

specify { expect(machine::X).to eq "x" }

specify { expect(machine::Y).to eq "y" }

context "initial" do
before { machine.state(:x, initial: true) }
before { machine.state(:z, initial: true) }

specify { expect(machine.initial_state).to eq("x") }
specify { expect(machine.initial_state).to eq("z") }

context "when an initial state is already defined" do
it "raises an error" do
Expand All @@ -25,6 +29,15 @@
end
end
end

context "when state name constant is already defined" do
it "warns about name conflict" do
machine.const_set(:SOME_CONST, "some const")
warning_message = "Name conflict: 'Class::SOME_CONST' is already defined\n"

expect { machine.state(:some_const) }.to output(warning_message).to_stderr
end
end
end

describe ".remove_state" do
Expand Down

0 comments on commit 751dd46

Please sign in to comment.