Skip to content

Commit

Permalink
Add optional block to associations find method (#141)
Browse files Browse the repository at this point in the history
Adds a bit more parity with ActiveRecord, allowing the usage of `Recipe.find do ...` and `Recipe.groups.find do...`
  • Loading branch information
barrerajl committed Jun 7, 2023
1 parent 9b327f5 commit c3933f5
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 6 deletions.
11 changes: 8 additions & 3 deletions lib/spyke/orm.rb
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
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
@@ -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
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
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

0 comments on commit c3933f5

Please sign in to comment.