Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add InvalidTransition exception with more helpful message. #30

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
9 changes: 6 additions & 3 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
attr_reader :events
Expand Down Expand Up @@ -66,9 +68,10 @@ def initialize(model, column, states, prefix, suffix, name, &block)
end

# def assign!()
detect_enum_conflict! column, "#{value_method_name}!"
define_method "#{value_method_name}!" do
send(value_method_name) || raise('Invalid transition')
value_method_name_bang = "#{value_method_name}!"
detect_enum_conflict! column, value_method_name_bang
define_method value_method_name_bang do
send(value_method_name) || raise(InvalidTransition.new(send(column), value_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