From 0b61e7afeb192366b713ea7acc7093f10e8d6352 Mon Sep 17 00:00:00 2001 From: Sergio Martin Date: Tue, 17 Nov 2015 17:51:18 +0100 Subject: [PATCH] Excludes state initialization when attribute is not included in the query --- lib/state_machines/integrations/mongoid.rb | 2 +- test/machine_with_limited_fields_test.rb | 26 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 test/machine_with_limited_fields_test.rb diff --git a/lib/state_machines/integrations/mongoid.rb b/lib/state_machines/integrations/mongoid.rb index 07b3236..e72e783 100644 --- a/lib/state_machines/integrations/mongoid.rb +++ b/lib/state_machines/integrations/mongoid.rb @@ -334,7 +334,7 @@ def apply_pre_processed_defaults defaults = {} self.class.state_machines.initialize_states(self, :static => :force, :dynamic => false, :to => defaults) defaults.each do |attr, value| - send(:"\#{attr}=", value) unless attributes.include?(attr) + send(:"\#{attr}=", value) unless has_attribute?(attr) || attribute_missing?(attr) end super end diff --git a/test/machine_with_limited_fields_test.rb b/test/machine_with_limited_fields_test.rb new file mode 100644 index 0000000..2dc6db9 --- /dev/null +++ b/test/machine_with_limited_fields_test.rb @@ -0,0 +1,26 @@ +require_relative 'test_helper' + +class MachineWithLimitedFieldsTest < BaseTestCase + def setup + @model = new_model + @machine = StateMachines::Machine.new(@model, :initial => :parked) + @machine.state :idling + + @record = @model.create + end + + def test_should_not_set_value_when_exclude_field_in_query + record = @model.where(id: @record.id).only(:_id).first + assert_equal ["_id"], record.attributes.keys + end + + def test_should_set_value_when_include_field_in_query + record = @model.where(id: @record.id).only(:_id, :state).first + assert_equal "parked", record.state + end + + def test_should_fail_if_access_when_exclude_field_in_query + record = @model.where(id: @record.id).only(:_id).first + assert_raises(ActiveModel::MissingAttributeError) { record.state } + end +end