Skip to content

Instantly share code, notes, and snippets.

@csexton
Last active August 29, 2015 14:20
Show Gist options
  • Save csexton/4ddcfa23cd9bfa4be5ee to your computer and use it in GitHub Desktop.
Save csexton/4ddcfa23cd9bfa4be5ee to your computer and use it in GitHub Desktop.
# Make this code more readable or remove duplication... or both!
require 'micromachine'
self.class.const_set(:Event, Class.new)
self.class.const_get(:Event).class_eval do
def method_missing(method_sym, *arguments, &block)
case method_sym
when :confirm!, :cancel!, :reset!
confirmation.method(:trigger)[method_sym.to_s.gsub('!','').to_sym]
when :confirmation_state
confirmation.send("state")
when :confirmation
@confirmation ||= MicroMachine.new(@confirmation_state || "pending").tap do |fsm|
fsm.when(:confirm, "pending" => "confirmed")
fsm.when(:cancel, "confirmed" => "cancelled")
fsm.when(:reset, "confirmed" => "pending", "cancelled" => "pending")
end
end
end
end
require 'minitest/autorun'
describe Event do
let(:event){ Event.new }
it "begins as pending" do
_(event.confirmation_state).must_equal "pending"
end
it "transitions from pending to confirmed" do
event.confirm!
_(event.confirmation_state).must_equal "confirmed"
end
it "transitions from confirmed to cancelled" do
event.confirm!
_(event.confirmation_state).must_equal "confirmed"
event.cancel!
_(event.confirmation_state).must_equal "cancelled"
end
it "transitions from confirmed to pending" do
event.confirm!
_(event.confirmation_state).must_equal "confirmed"
event.reset!
_(event.confirmation_state).must_equal "pending"
end
it "transitions from cancelled to pending" do
event.confirm!
event.cancel!
_(event.confirmation_state).must_equal "cancelled"
event.reset!
_(event.confirmation_state).must_equal "pending"
end
it "remains pending if cancelled" do
event.cancel!
_(event.confirmation_state).must_equal "pending"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment