Skip to content

Commit

Permalink
When a Symbol with an "as" Alias is present, handle it correctly
Browse files Browse the repository at this point in the history
Fixes girishso#20

Extract separation logic into a new function and make the regex into
a constant
  • Loading branch information
Jake Yesbeck committed Oct 3, 2018
1 parent 978468a commit c513c6f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
15 changes: 13 additions & 2 deletions lib/pluck_to_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions spec/support/shared_examples.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit c513c6f

Please sign in to comment.