Skip to content

Commit

Permalink
Add InvalidTransition exception with more helpful message.
Browse files Browse the repository at this point in the history
  • Loading branch information
ordinaryzelig committed Mar 28, 2018
1 parent b6c3430 commit af1194c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
11 changes: 11 additions & 0 deletions lib/stateful_enum/invalid_transition.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module StatefulEnum
class InvalidTransition < StandardError
attr_reader :state
attr_reader :event

def initialize(state, event)
@state, @event = state, event
super("Invalid transition from state #{@state.inspect} via event #{@event.inspect}")
end
end
end
7 changes: 5 additions & 2 deletions lib/stateful_enum/machine.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require 'stateful_enum/invalid_transition'

module StatefulEnum
class Machine
def initialize(model, column, states, prefix, suffix, &block)
Expand Down Expand Up @@ -63,9 +65,10 @@ def initialize(model, column, states, prefix, suffix, name, &block)
end

# def assign!()
detect_enum_conflict! column, "#{new_method_name}!"
new_method_name_bang = "#{new_method_name}!"
detect_enum_conflict! column, new_method_name_bang
define_method "#{new_method_name}!" do
send(new_method_name) || raise('Invalid transition')
send(new_method_name) || raise(InvalidTransition.new(send(column), new_method_name_bang.to_sym))
end

# def can_assign?()
Expand Down
10 changes: 7 additions & 3 deletions test/mechanic_machine_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,14 @@ def test_invalid_transition
def test_invalid_transition!
bug = Bug.new
bug.resolve!
assert_raises do
bug.assign!
end
exception =
assert_raises(StatefulEnum::InvalidTransition) do
bug.assign!
end
assert_equal 'resolved', bug.status
assert_equal 'Invalid transition from state "resolved" via event :assign!', exception.message
assert_equal 'resolved', exception.state
assert_equal :assign!, exception.event
end

def test_can_xxxx?
Expand Down

0 comments on commit af1194c

Please sign in to comment.