From 027e21ff77b0a7c4000a08ac191f75c269c7c56d Mon Sep 17 00:00:00 2001 From: khiav reoy Date: Sun, 30 Jul 2023 13:47:20 +0800 Subject: [PATCH] refactoring by adding cast_values method --- gemfiles/active_record_70.gemfile | 2 +- lib/pluck_all/models/active_record_extension.rb | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/gemfiles/active_record_70.gemfile b/gemfiles/active_record_70.gemfile index 8e3635c..e49e4b5 100644 --- a/gemfiles/active_record_70.gemfile +++ b/gemfiles/active_record_70.gemfile @@ -4,7 +4,7 @@ source 'https://rubygems.org' gem 'sqlite3', '~> 1.4.1' gem 'zeitwerk' -gem 'activerecord', '~> 7.0.0' +gem 'activerecord', '~> 7.0.6' gem 'rails_compatibility', '~> 0.0.7' gem 'carrierwave', '~> 0.11.0' diff --git a/lib/pluck_all/models/active_record_extension.rb b/lib/pluck_all/models/active_record_extension.rb index 4bc8ff2..ed88a47 100644 --- a/lib/pluck_all/models/active_record_extension.rb +++ b/lib/pluck_all/models/active_record_extension.rb @@ -57,18 +57,24 @@ def pluck_all(*column_names, cast_uploader_url: true) return RailsCompatibility.apply_join_dependency(self).pluck_all(*column_names) if has_include result = select_all(column_names) + return cast_values(result, cast_uploader_url) + end + + private + + # Please refer to the 'cast_values' method in the 'active_record/result.rb' file to see the original implementation of `pluck` method. + def cast_values(result, cast_uploader_url) attribute_types = RailsCompatibility.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) # TODO: 現在AS過後的type cast會有一點問題,但似乎原生的pluck也有此問題 + attributes[key] = result.send(:column_type, key, attribute_types).deserialize(attribute) end cast_carrier_wave_uploader_url(attributes) if cast_uploader_url next attributes end end - private - def to_sql_column_name proc do |column_name| if column_name.is_a?(Arel::Attributes::Attribute)