Skip to content

Commit

Permalink
Add Model.pluck method like ActiveRecord: http://api.rubyonrails.org/…
Browse files Browse the repository at this point in the history
  • Loading branch information
huacnlee committed Sep 3, 2012
1 parent fec64f8 commit 64a8c14
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/mongoid/finders.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,17 @@ def first
def last
with_default_scope.last
end

# Pick up values array by a column
#
# @example Pick up all email from User model
# User.pluck(:email)
#
# @return [ Array ] The all values in column
def pluck(column_name)
column_name = column_name.to_sym
with_default_scope.all.only([column_name]).map(&column_name)
end

protected

Expand All @@ -144,5 +155,6 @@ def last
def find_or(method, attrs = {}, &block)
where(attrs).first || send(method, attrs, &block)
end

end
end
25 changes: 25 additions & 0 deletions spec/mongoid/finders_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,31 @@
end
end
end


describe "#pluck" do
it "work" do
Person.create(title: "Senorita")
Person.create(title: "Jason")
Person.pluck(:title).should eq(%w(Senorita Jason))
end

context "work with Criteria" do
before do
Person.create(title: "Senorita")
Person.create(title: "Jason", pets: true)
Person.create(title: "Tim")
end

it "with where" do
Person.where(pets: false).pluck(:title).should eq(%w(Senorita Tim))
end

it "with limit" do
Person.where(pets: false).limit(1).pluck(:title).should eq(%w(Senorita))
end
end
end

Origin::Selectable.forwardables.each do |method|

Expand Down

0 comments on commit 64a8c14

Please sign in to comment.