1
0
Fork 0
mirror of https://github.com/aasm/aasm synced 2023-03-27 23:22:41 -04:00

allow multiple states to be defined on one line

This commit is contained in:
Adam Hess 2015-12-02 02:38:56 -07:00
parent f5c9bfe5b5
commit afe64b10cb
5 changed files with 52 additions and 12 deletions

View file

@ -28,8 +28,7 @@ class Job
aasm do aasm do
state :sleeping, :initial => true state :sleeping, :initial => true
state :running state :running, :cleaning
state :cleaning
event :run do event :run do
transitions :from => :sleeping, :to => :running transitions :from => :sleeping, :to => :running

View file

@ -63,21 +63,39 @@ module AASM
end end
# define a state # define a state
def state(name, options={}) # args
@state_machine.add_state(name, @klass, options) # [0] state
# [1] options (or nil)
if @klass.instance_methods.include?("#{name}?") # or
warn "#{@klass.name}: The aasm state name #{name} is already used!" # [0] state
# [1..] state
def state(*args)
if args.last.is_a?(Hash) && args.size == 2
names = [args.first]
options = args.last
elsif
names = args
options = {}
else
raise "count not parse states: #{args}"
end end
@klass.class_eval <<-EORUBY, __FILE__, __LINE__ + 1 names.each do |name|
@state_machine.add_state(name, @klass, options)
if @klass.instance_methods.include?("#{name}?")
warn "#{@klass.name}: The aasm state name #{name} is already used!"
end
@klass.class_eval <<-EORUBY, __FILE__, __LINE__ + 1
def #{name}? def #{name}?
aasm(:#{@name}).current_state == :#{name} aasm(:#{@name}).current_state == :#{name}
end end
EORUBY EORUBY
unless @klass.const_defined?("STATE_#{name.upcase}") unless @klass.const_defined?("STATE_#{name.upcase}")
@klass.const_set("STATE_#{name.upcase}", name) @klass.const_set("STATE_#{name.upcase}", name)
end
end end
end end

View file

@ -0,0 +1,8 @@
class StatesOnOneLineExample
include AASM
aasm :one_line do
state :initial, :initial => true
state :first, :second
end
end

View file

@ -8,8 +8,7 @@ describe 'testing the README examples' do
aasm do aasm do
state :sleeping, :initial => true state :sleeping, :initial => true
state :running state :running, :cleaning
state :cleaning
event :run do event :run do
transitions :from => :sleeping, :to => :running transitions :from => :sleeping, :to => :running

View file

@ -0,0 +1,16 @@
require 'spec_helper'
describe StatesOnOneLineExample do
let(:example) { StatesOnOneLineExample.new }
describe 'on initialize' do
it 'should be in the initial state' do
expect(example.aasm(:one_line).current_state).to eql :initial
end
end
describe 'states' do
it 'should have all 3 states defined' do
expect(example.aasm(:one_line).states.map(&:name)).to eq [:initial, :first, :second]
end
end
end