Skip to content

Commit

Permalink
Handle passing an array of ids to find
Browse files Browse the repository at this point in the history
This improves the method signature to be closer to that of `ActiveRecord::Base#find`.

The return value of find is always an array when an array is passed
as an argument. e.g.:

    User.find(1)   # => #<User id=1>
    User.find([1]) # => [#<User id=1>]
  • Loading branch information
thomsbg committed Aug 21, 2012
1 parent 3ff1775 commit 67c4a4e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
16 changes: 6 additions & 10 deletions lib/her/model/orm.rb
Expand Up @@ -77,23 +77,19 @@ def invalid? # {{{
# # Fetched via GET "/users/1"
#
# @example
# @users = User.find(1, 2)
# @users = User.find([1, 2])
# # Fetched via GET "/users/1" and GET "/users/2"
def find(*ids) # {{{
params = ids.last.is_a?(Hash) ? ids.pop : {}
results = ids.map do |id|
request_params = params.merge(
:_method => :get,
:_path => "#{build_request_path(params.merge(:id => id))}"
)
request(request_params) do |parsed_data|
results = ids.flatten.compact.uniq.map do |id|
request(params.merge(:_method => :get, :_path => "#{build_request_path(params.merge(:id => id))}")) do |parsed_data|
new(parsed_data[:data])
end
end
if ids.length == 1
results.first
else
if ids.length > 1 || ids.first.kind_of?(Array)
results
else
results.first
end
end # }}}

Expand Down
15 changes: 15 additions & 0 deletions spec/model/orm_spec.rb
Expand Up @@ -186,6 +186,21 @@ def organization=(organization)
@users[1].id.should == 2
end # }}}

it "handles finding by an array of ids" do
@users = User.find([1, 2])
@users.should be_kind_of(Array)
@users.length.should == 2
@users[0].id.should == 1
@users[1].id.should == 2
end

it "handles finding by an array of ids of length 1" do
@users = User.find([1])
@users.should be_kind_of(Array)
@users.length.should == 1
@users[0].id.should == 1
end

it "handles finding with other parameters" do # {{{
@users = User.all(:age => 42)
@users.should be_kind_of(Array)
Expand Down

0 comments on commit 67c4a4e

Please sign in to comment.