Skip to content

Commit

Permalink
Map attribute aliases to column names when initializing
Browse files Browse the repository at this point in the history
  • Loading branch information
joelvh committed Apr 16, 2021
1 parent 29f34b9 commit c85988a
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/state_machines/integrations/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,7 @@ 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)
self.class.state_machines.initialize_states(self, {}, scoped_attributes)
Expand All @@ -466,6 +467,7 @@ 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)
super(attributes, options) do |*args|
Expand Down
6 changes: 6 additions & 0 deletions test/machine_with_aliased_attribute_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,11 @@ 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

0 comments on commit c85988a

Please sign in to comment.