From 1b422a537f3700da140128bf94486431bc89b9e7 Mon Sep 17 00:00:00 2001 From: James Herdman Date: Fri, 15 Mar 2013 00:00:22 -0400 Subject: [PATCH] AASM defines constants for each state name Example: class Foo include AASM aasm do state :initialized state :calculated state :finalized end end > Foo::STATE_INITIALIZED => :initialized > Foo::STATE_CALCULATED => :calculated You may find this useful in custom scopes when using ActiveRecord, or when testing your classes. --- CHANGELOG.md | 4 ++++ lib/aasm/base.rb | 4 ++++ spec/unit/simple_example_spec.rb | 6 ++++++ 3 files changed, 14 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 47eca82..f986d44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # CHANGELOG +## Unreleased + + * added autocreation of constants for each state ([@jherdman](https://github.com/jherdman)) + ## 3.0.16 * added autocreation of state scopes for Mongoid (thanks to [@jonnyshields](https://github.com/johnnyshields)) diff --git a/lib/aasm/base.rb b/lib/aasm/base.rb index 770f418..2606f3f 100644 --- a/lib/aasm/base.rb +++ b/lib/aasm/base.rb @@ -32,6 +32,10 @@ module AASM @clazz.send(:define_method, "#{name.to_s}?") do aasm_current_state == name end + + unless @clazz.const_defined?("STATE_#{name.to_s.upcase}") + @clazz.const_set("STATE_#{name.to_s.upcase}", name) + end end # define an event diff --git a/spec/unit/simple_example_spec.rb b/spec/unit/simple_example_spec.rb index 6265a72..b7a5c61 100644 --- a/spec/unit/simple_example_spec.rb +++ b/spec/unit/simple_example_spec.rb @@ -50,4 +50,10 @@ describe 'state machine' do lambda {payment.fill_out}.should raise_error(AASM::InvalidTransition) lambda {payment.fill_out!}.should raise_error(AASM::InvalidTransition) end + + it 'defines constants for each state name' do + Payment::STATE_INITIALISED.should eq(:initialised) + Payment::STATE_FILLED_OUT.should eq(:filled_out) + Payment::STATE_AUTHORISED.should eq(:authorised) + end end