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

Add optional block to associations find method #141

Merged
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: 8 additions & 3 deletions lib/spyke/orm.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,14 @@ def method_for(callback, value = nil)
callback_methods[callback]
end

def find(id)
raise ResourceNotFound if id.blank?
where(primary_key => id).find_one || raise(ResourceNotFound)
def find(id = nil, &block)
if block_given?
all.find_some.find(&block)
else
raise ResourceNotFound if id.blank?

where(primary_key => id).find_one || raise(ResourceNotFound)
end
end

def fetch
Expand Down
4 changes: 2 additions & 2 deletions lib/spyke/relation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ def with_fallback(fallback = nil)
end

# Overrides Enumerable find
def find(id)
scoping { klass.find(id) }
def find(id = nil, &block)
scoping { klass.find(id, &block) }
end

def find_one
Expand Down
2 changes: 1 addition & 1 deletion lib/spyke/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module Spyke
VERSION = '7.0.0'
VERSION = '7.1.0'
end
8 changes: 8 additions & 0 deletions test/associations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,14 @@ def test_array_like_behavior
assert_equal 'Fish', recipe.groups.first.name
end

def test_find_with_block
stub_request(:get, 'http://sushi.com/recipes/1/groups').to_return_json(result: [{ name: 'Fish' }, { name: 'Fruit' }, { name: 'Bread' }])

recipe = Recipe.new(id: 1)

assert_equal 'Fruit', recipe.groups.find { |g| g.name == 'Fruit' }.name
end

def test_nil_has_one_association
stub_request(:get, 'http://sushi.com/recipes/1/image')

Expand Down
10 changes: 10 additions & 0 deletions test/orm_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ def test_find
assert_equal 'Bob', user.name
end

def test_find_with_block
stub_request(:get, 'http://sushi.com/users').to_return_json(result: [{ id: 1, name: 'Bob' }, id: 2, name: 'Alice'])

user = User.find do |u|
u.name == 'Bob'
end

assert_equal 'Bob', user.name
end

def test_reload
stub_request(:get, 'http://sushi.com/recipes/1').to_return_json(result: { id: 1, title: 'Sushi' })

Expand Down