From ebb36e697dd9e1b9e4cfc98b9ee9b3399d23ef46 Mon Sep 17 00:00:00 2001 From: Scott Barron Date: Fri, 22 Feb 2008 15:46:31 -0500 Subject: [PATCH] Some automatic persistence hooks for ActiveRecord objects --- lib/aasm.rb | 4 ++- lib/persistence.rb | 13 +++++++ lib/persistence/active_record_persistence.rb | 36 ++++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 lib/persistence.rb create mode 100644 lib/persistence/active_record_persistence.rb diff --git a/lib/aasm.rb b/lib/aasm.rb index 3b58889..b7f3c7e 100644 --- a/lib/aasm.rb +++ b/lib/aasm.rb @@ -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 diff --git a/lib/persistence.rb b/lib/persistence.rb new file mode 100644 index 0000000..b75d808 --- /dev/null +++ b/lib/persistence.rb @@ -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 diff --git a/lib/persistence/active_record_persistence.rb b/lib/persistence/active_record_persistence.rb new file mode 100644 index 0000000..11e0782 --- /dev/null +++ b/lib/persistence/active_record_persistence.rb @@ -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