diff --git a/lib/spyke/orm.rb b/lib/spyke/orm.rb index c367ea7..d7ecad6 100644 --- a/lib/spyke/orm.rb +++ b/lib/spyke/orm.rb @@ -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 diff --git a/lib/spyke/relation.rb b/lib/spyke/relation.rb index 8e3b340..2e7f59c 100644 --- a/lib/spyke/relation.rb +++ b/lib/spyke/relation.rb @@ -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 diff --git a/lib/spyke/version.rb b/lib/spyke/version.rb index 419bede..4adab6d 100644 --- a/lib/spyke/version.rb +++ b/lib/spyke/version.rb @@ -1,3 +1,3 @@ module Spyke - VERSION = '7.0.0' + VERSION = '7.1.0' end diff --git a/test/associations_test.rb b/test/associations_test.rb index dde2436..9bd6195 100644 --- a/test/associations_test.rb +++ b/test/associations_test.rb @@ -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') diff --git a/test/orm_test.rb b/test/orm_test.rb index 290d9b3..199a47d 100644 --- a/test/orm_test.rb +++ b/test/orm_test.rb @@ -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' })