Invoke original inherited callback when subclassed

When AASM is included into a class, it defines inherited, clobbering
the original definition.  This problem becomes readily apparent with STI
in Rails, where the original method is part of the implementation of
inheritable attributes, a feature relied on for several ActiveRecord
features such as callbacks and timestamp recording.

Move the implementation of inherited to ClassMethods and invoke the
original method via super.
This commit is contained in:
Tim Pope 2008-10-09 18:55:45 -04:00
parent f44a808636
commit fee9487e0d
2 changed files with 15 additions and 6 deletions

View File

@ -18,15 +18,14 @@ module AASM
base.extend AASM::ClassMethods
AASM::Persistence.set_persistence(base)
AASM::StateMachine[base] = AASM::StateMachine.new('')
base.class_eval do
def base.inherited(klass)
AASM::StateMachine[klass] = AASM::StateMachine[self].dup
end
end
end
module ClassMethods
def inherited(klass)
AASM::StateMachine[klass] = AASM::StateMachine[self].dup
super
end
def aasm_initial_state(set_state=nil)
if set_state
AASM::StateMachine[self].initial_state = set_state

View File

@ -70,6 +70,16 @@ describe AASM, '- class level definitions' do
end
describe AASM, '- when included' do
it 'should invoke the original inherited callback when subclassed' do
parent = Class.new
parent.should_receive(:inherited)
parent.send(:include, AASM)
child = Class.new(parent)
end
end
describe AASM, '- aasm_states_for_select' do
it "should return a select friendly array of states in the form of [['Friendly name', 'state_name']]" do
Foo.aasm_states_for_select.should == [['Open', 'open'], ['Closed', 'closed']]