From c513c6fcb8af5042bd185fbd02432e130a9ef4b8 Mon Sep 17 00:00:00 2001 From: Jake Yesbeck Date: Wed, 3 Oct 2018 19:32:21 -0400 Subject: [PATCH] When a Symbol with an "as" Alias is present, handle it correctly Fixes #20 Extract separation logic into a new function and make the regex into a constant --- lib/pluck_to_hash.rb | 15 +++++++++++++-- spec/support/shared_examples.rb | 6 ++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/pluck_to_hash.rb b/lib/pluck_to_hash.rb index a1b6630..eb9d2fa 100644 --- a/lib/pluck_to_hash.rb +++ b/lib/pluck_to_hash.rb @@ -4,6 +4,9 @@ module PluckToHash extend ActiveSupport::Concern module ClassMethods + + AS_REGEX = /\bas\b/i + def pluck_to_hash(*keys) block_given = block_given? hash_type = keys[-1].is_a?(Hash) ? keys.pop.fetch(:hash_type,HashWithIndifferentAccess) : HashWithIndifferentAccess @@ -44,15 +47,23 @@ def format_keys(keys) keys.map do |k| case k when String - k.split(/\bas\b/i)[-1].strip.to_sym + extract_as(k) when Symbol - k + if !(k.to_s =~ AS_REGEX).nil? + extract_as(k.to_s) + else + k + end end end ] end end + def extract_as(input) + input.split(AS_REGEX)[-1].strip.to_sym + end + alias_method :pluck_h, :pluck_to_hash alias_method :pluck_s, :pluck_to_struct end diff --git a/spec/support/shared_examples.rb b/spec/support/shared_examples.rb index 48f1fa1..2dbbfa8 100644 --- a/spec/support/shared_examples.rb +++ b/spec/support/shared_examples.rb @@ -22,6 +22,12 @@ end end + it 'pluck field with symbol alias' do + TestModel.all.pluck_to_hash(:'id as something').each do |hash| + expect(hash).to have_key(:something) + end + end + it 'pluck field with uppercase alias' do TestModel.all.pluck_to_hash('id AS otherfield').each do |hash| expect(hash).to have_key(:otherfield)