mirror of
https://github.com/aasm/aasm
synced 2023-03-27 23:22:41 -04:00
Some automatic persistence hooks for ActiveRecord objects
This commit is contained in:
parent
ea7820db4a
commit
ebb36e697d
3 changed files with 52 additions and 1 deletions
|
@ -1,5 +1,6 @@
|
|||
require File.join(File.dirname(__FILE__), 'event')
|
||||
require File.join(File.dirname(__FILE__), 'state')
|
||||
require File.join(File.dirname(__FILE__), 'persistence')
|
||||
|
||||
module AASM
|
||||
class InvalidTransition < Exception
|
||||
|
@ -7,6 +8,7 @@ module AASM
|
|||
|
||||
def self.included(base) #:nodoc:
|
||||
base.extend AASM::ClassMethods
|
||||
AASM::Persistence.set_persistence(base)
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
|
@ -63,7 +65,7 @@ module AASM
|
|||
if self.respond_to?(:aasm_read_state) || self.private_methods.include?('aasm_read_state')
|
||||
@aasm_current_state = aasm_read_state
|
||||
end
|
||||
return @aasm_read_state if @aasm_current_state
|
||||
return @aasm_current_state if @aasm_current_state
|
||||
self.class.aasm_initial_state
|
||||
end
|
||||
|
||||
|
|
13
lib/persistence.rb
Normal file
13
lib/persistence.rb
Normal file
|
@ -0,0 +1,13 @@
|
|||
module AASM
|
||||
module Persistence
|
||||
def self.set_persistence(base)
|
||||
# Use a fancier auto-loading thingy, perhaps. When there are more persistence engines.
|
||||
hierarchy = base.ancestors.map {|klass| klass.to_s}
|
||||
|
||||
if hierarchy.include?("ActiveRecord::Base")
|
||||
require File.join(File.dirname(__FILE__), 'persistence', 'active_record_persistence')
|
||||
base.send(:include, AASM::Persistence::ActiveRecordPersistence)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
36
lib/persistence/active_record_persistence.rb
Normal file
36
lib/persistence/active_record_persistence.rb
Normal file
|
@ -0,0 +1,36 @@
|
|||
module AASM
|
||||
module Persistence
|
||||
module ActiveRecordPersistence
|
||||
def self.included(base)
|
||||
base.extend AASM::Persistence::ActiveRecordPersistence::ClassMethods
|
||||
base.send(:include, AASM::Persistence::ActiveRecordPersistence::WriteState) unless base.method_defined?(:aasm_write_state)
|
||||
base.send(:include, AASM::Persistence::ActiveRecordPersistence::ReadState) unless base.method_defined?(:aasm_read_state)
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
def aasm_column(column_name=nil)
|
||||
if column_name
|
||||
@aasm_column = column_name.to_sym
|
||||
else
|
||||
@aasm_column
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
module WriteState
|
||||
def aasm_write_state(state)
|
||||
@aasm_column ||= :aasm_state
|
||||
|
||||
update_attribute(@aasm_column, state.to_s)
|
||||
end
|
||||
end
|
||||
|
||||
module ReadState
|
||||
def aasm_read_state
|
||||
@aasm_column ||= :aasm_state
|
||||
send(@aasm_column).to_sym
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue