Skip to content

Commit af1194c

Browse files
committed
Add InvalidTransition exception with more helpful message.
1 parent b6c3430 commit af1194c

File tree

3 files changed

+23
-5
lines changed

3 files changed

+23
-5
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
module StatefulEnum
2+
class InvalidTransition < StandardError
3+
attr_reader :state
4+
attr_reader :event
5+
6+
def initialize(state, event)
7+
@state, @event = state, event
8+
super("Invalid transition from state #{@state.inspect} via event #{@event.inspect}")
9+
end
10+
end
11+
end

lib/stateful_enum/machine.rb

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# frozen_string_literal: true
22

3+
require 'stateful_enum/invalid_transition'
4+
35
module StatefulEnum
46
class Machine
57
def initialize(model, column, states, prefix, suffix, &block)
@@ -63,9 +65,10 @@ def initialize(model, column, states, prefix, suffix, name, &block)
6365
end
6466

6567
# def assign!()
66-
detect_enum_conflict! column, "#{new_method_name}!"
68+
new_method_name_bang = "#{new_method_name}!"
69+
detect_enum_conflict! column, new_method_name_bang
6770
define_method "#{new_method_name}!" do
68-
send(new_method_name) || raise('Invalid transition')
71+
send(new_method_name) || raise(InvalidTransition.new(send(column), new_method_name_bang.to_sym))
6972
end
7073

7174
# def can_assign?()

test/mechanic_machine_test.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,14 @@ def test_invalid_transition
4545
def test_invalid_transition!
4646
bug = Bug.new
4747
bug.resolve!
48-
assert_raises do
49-
bug.assign!
50-
end
48+
exception =
49+
assert_raises(StatefulEnum::InvalidTransition) do
50+
bug.assign!
51+
end
5152
assert_equal 'resolved', bug.status
53+
assert_equal 'Invalid transition from state "resolved" via event :assign!', exception.message
54+
assert_equal 'resolved', exception.state
55+
assert_equal :assign!, exception.event
5256
end
5357

5458
def test_can_xxxx?

0 commit comments

Comments
 (0)