Skip to content

Commit

Permalink
Implement #cast_values
Browse files Browse the repository at this point in the history
  • Loading branch information
khiav reoy committed Jul 30, 2023
1 parent 1313f43 commit 3f87fa5
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
33 changes: 33 additions & 0 deletions lib/rails_compatibility/cast_values.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# frozen_string_literal: true

require 'rails_compatibility'
require 'rails_compatibility/active_record'

class << RailsCompatibility
if Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('7.0.6')
# Rails 7.0.6 changes parameter handling. Details at: https://github.com/rails/rails/pull/45783
def cast_values(klass, result)
attribute_types = self.attribute_types(klass)

result.map do |attributes| # This map behaves different to array#map
attributes.each_with_index do |(key, attribute), index|
attributes[key] = result.send(:column_type, key, index, attribute_types).deserialize(attribute)
end

next attributes
end
end
else
def cast_values(klass, result)
attribute_types = self.attribute_types(klass)

result.map do |attributes| # This map behaves different to array#map
attributes.each do |key, attribute|
attributes[key] = result.send(:column_type, key, attribute_types).deserialize(attribute)
end

next attributes
end
end
end
end
15 changes: 15 additions & 0 deletions test/cast_values_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# frozen_string_literal: true

require 'test_helper'
require 'rails_compatibility/cast_values'

class CastValuesTest < Minitest::Test
def setup
end

def test_cast_values
sql = 'SELECT `users`.`name` FROM `users` WHERE `users`.`name` = "Peter" LIMIT 1'
result = ActiveRecord::Base.connection.select_all(sql)
assert_equal ['name' => 'Peter'], RailsCompatibility.cast_values(User, result)
end
end

0 comments on commit 3f87fa5

Please sign in to comment.