Skip to content

Commit 4b33d12

Browse files
author
Derek Lindahl
committed
Add .find_by! and .find_by methods to Resource
1 parent 1adbd0b commit 4b33d12

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,15 @@ like so:
349349
> Order.find(1)
350350
# <Order id=1 total=54.47>
351351

352+
> Order.find_by(id:1)
353+
# <Order id=1 total=54.47>
354+
355+
> Order.find_by!(id:-1, state:'active')
356+
# Frenetic::ResourceNotFound: Couldn't find Order with id=-1, state=active
357+
358+
> Order.find_by(id:-1)
359+
# nil
360+
352361
> Order.all
353362
# [<Order id=1 total=54.47>,<Order id=2 total=42.00>]
354363
```

lib/frenetic/concerns/member_rest_methods.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,16 @@ def find(params)
1818
new(response.body) if response.success?
1919
end
2020

21+
def find_by!(params)
22+
find(params)
23+
end
24+
25+
def find_by(params)
26+
find_by!(params)
27+
rescue ClientError
28+
nil
29+
end
30+
2131
def all
2232
return [] if test_mode?
2333
response = api.get(collection_url)

spec/concerns/member_rest_methods_spec.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,25 @@
8585
end
8686
end
8787

88+
describe '.find_by' do
89+
before { @stubs.api_description }
90+
91+
subject { MyTempResource.find_by(id:1) }
92+
93+
it 'delegates to .find' do
94+
allow(MyTempResource).to receive(:find).and_return(nil)
95+
subject
96+
expect(MyTempResource).to have_received(:find)
97+
end
98+
99+
context 'for an unknown resource' do
100+
it 'returns nil' do
101+
allow(MyTempResource).to receive(:find).and_raise(Frenetic::ClientError.new({}))
102+
expect{subject}.to_not raise_error
103+
end
104+
end
105+
end
106+
88107
describe '.all' do
89108
before { @stubs.api_description }
90109

0 commit comments

Comments
 (0)