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

Fix #pluck method behavior when 3+ attributes specified #269

Merged
merged 2 commits into from
Nov 28, 2022
Merged
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
11 changes: 10 additions & 1 deletion lib/active_hash/relation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,16 @@ def size
end

def pluck(*column_names)
column_names.map { |column_name| all.map(&column_name.to_sym) }.inject(&:zip)
symbolized_column_names = column_names.map(&:to_sym)

if symbolized_column_names.length == 1
column_name = symbolized_column_names.first
all.map { |record| record[column_name] }
else
all.map do |record|
symbolized_column_names.map { |column_name| record[column_name] }
end
end
end

def ids
Expand Down
15 changes: 10 additions & 5 deletions spec/active_hash/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -527,17 +527,22 @@ class Region < ActiveHash::Base
describe ".pluck" do
before do
Country.data = [
{:id => 1, :name => "US"},
{:id => 2, :name => "Canada"}
{:id => 1, :name => "US", :language => "English"},
{:id => 2, :name => "Canada", :language => "English"},
{:id => 3, :name => "Mexico", :language => "Spanish"}
]
end

it "returns an two dimensional Array of attributes values" do
expect(Country.pluck(:id, :name)).to match_array([[1,"US"], [2, "Canada"]])
it "returns an two dimensional Array of 3 attributes values" do
expect(Country.pluck(:id, :name, :language)).to match_array([[1, "US", "English"], [2, "Canada", "English"], [3, "Mexico", "Spanish"]])
end

it "returns an two dimensional Array of 2 attributes values" do
expect(Country.pluck(:id, :name)).to match_array([[1, "US"], [2, "Canada"], [3, "Mexico"]])
end

it "returns an Array of attribute values" do
expect(Country.pluck(:id)).to match_array([1,2])
expect(Country.pluck(:id)).to match_array([1, 2, 3])
end
end

Expand Down