Skip to content

Commit

Permalink
Fix implementation to map aliased to original attribute names
Browse files Browse the repository at this point in the history
  • Loading branch information
joelvh committed Apr 17, 2021
1 parent c85988a commit bb1ab2a
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 8 deletions.
4 changes: 2 additions & 2 deletions lib/state_machines/integrations/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -456,8 +456,8 @@ def define_state_initializer
define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
def initialize(attributes = nil, *)
super(attributes) do |*args|
attributes = attributes.transform_keys { |key| self.class.attribute_aliases[key.to_s] || key }
scoped_attributes = (attributes || {}).merge(self.class.scope_attributes)
scoped_attributes.transform_keys! { |key| self.class.attribute_aliases[key.to_s] || key.to_s }
self.class.state_machines.initialize_states(self, {}, scoped_attributes)
yield(*args) if block_given?
Expand All @@ -467,8 +467,8 @@ def initialize(attributes = nil, *)
elsif ::ActiveRecord.gem_version >= Gem::Version.new('4.2')
define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
def initialize(attributes = nil, options = {})
attributes = attributes.transform_keys { |key| self.class.attribute_aliases[key.to_s] || key }
scoped_attributes = (attributes || {}).merge(self.class.scope_attributes)
scoped_attributes.transform_keys! { |key| self.class.attribute_aliases[key.to_s] || key.to_s }
super(attributes, options) do |*args|
self.class.state_machines.initialize_states(self, {}, scoped_attributes)
Expand Down
6 changes: 0 additions & 6 deletions test/machine_with_aliased_attribute_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,5 @@ def test_should_check_custom_attribute_for_predicate
@record.vehicle_status = 'parked'
assert @record.status?(:parked)
end

def test_should_initialize_with_original_attribute_names
record = @model.new(:vehicle_status => 'bogus')
refute record.status?(:parked)
assert record.status?(:bogus)
end
end

20 changes: 20 additions & 0 deletions test/machine_with_initialized_aliased_attribute_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
require_relative 'test_helper'

class MachineWithInitializedAliasedAttributeTest < BaseTestCase
def setup
@model = new_model do
alias_attribute :custom_status, :state
end

@machine = StateMachines::Machine.new(@model, :initial => :parked, :attribute => :state)
@machine.state :started

@record = @model.new(:custom_status => :started)
end

def test_should_match_original_attribute_value
refute @record.state?(:parked)
assert @record.state?(:started)
end
end

0 comments on commit bb1ab2a

Please sign in to comment.