Skip to content

Commit

Permalink
refactoring by adding cast_values method
Browse files Browse the repository at this point in the history
  • Loading branch information
khiav reoy committed Jul 30, 2023
1 parent 8005714 commit fa736cb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
2 changes: 1 addition & 1 deletion gemfiles/active_record_70.gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
15 changes: 11 additions & 4 deletions lib/pluck_all/models/active_record_extension.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,26 @@ def pluck_all(*column_names, cast_uploader_url: true)
has_include = RailsCompatibility.has_include?(self, column_names.first)
return RailsCompatibility.apply_join_dependency(self).pluck_all(*column_names) if has_include

result = select_all(column_names)
columns = arel_columns(column_names)
result = select_all(columns)
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)
Expand Down

0 comments on commit fa736cb

Please sign in to comment.