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

support turning off and on the configuration option for no_direct_assignment

This commit is contained in:
Thorsten Böttger 2015-05-29 22:41:31 +12:00
parent 7984528e07
commit daf13541bc
3 changed files with 30 additions and 6 deletions

View file

@ -27,11 +27,19 @@ module AASM
configure :enum, nil
if @state_machine.config.no_direct_assignment
@klass.send(:define_method, "#{@state_machine.config.column}=") do |state_name|
raise AASM::NoDirectAssignmentError.new('direct assignment of AASM column has been disabled (see AASM configuration for this class)')
# make sure to raise an error if no_direct_assignment is enabled
# and attribute is directly assigned though
@klass.class_eval %Q(
def #{@state_machine.config.column}=(state_name)
if self.class.aasm.state_machine.config.no_direct_assignment
raise AASM::NoDirectAssignmentError.new(
'direct assignment of AASM column has been disabled (see AASM configuration for this class)'
)
else
super
end
end
end
)
end
# This method is both a getter and a setter

View file

@ -1,8 +1,6 @@
class LocalizerTestModel < ActiveRecord::Base
include AASM
attr_accessor :aasm_state
aasm do
state :opened, :initial => true
state :closed

View file

@ -321,6 +321,24 @@ describe "direct assignment" do
expect {obj.aasm_state = :running}.to raise_error(AASM::NoDirectAssignmentError)
expect(obj.aasm_state.to_sym).to eql :pending
end
it 'can be turned off and on again' do
obj = NoDirectAssignment.create
expect(obj.aasm_state.to_sym).to eql :pending
expect {obj.aasm_state = :running}.to raise_error(AASM::NoDirectAssignmentError)
expect(obj.aasm_state.to_sym).to eql :pending
# allow it temporarily
NoDirectAssignment.aasm.state_machine.config.no_direct_assignment = false
obj.aasm_state = :pending
expect(obj.aasm_state.to_sym).to eql :pending
# and forbid it again
NoDirectAssignment.aasm.state_machine.config.no_direct_assignment = true
expect {obj.aasm_state = :running}.to raise_error(AASM::NoDirectAssignmentError)
expect(obj.aasm_state.to_sym).to eql :pending
end
end # direct assignment
describe 'initial states' do