Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When a Symbol with an "as" Alias is present, handle it correctly #27

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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