From 7a867c3e15ecb90a30572088d2b493960e11b297 Mon Sep 17 00:00:00 2001 From: Kevin Bongart Date: Sun, 31 Jul 2016 11:40:08 -0400 Subject: [PATCH] Don't raise KeyError when trying to navigate to nil next_page --- .../linking/top_level_links.rb | 1 + test/unit/top_level_links_test.rb | 45 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/lib/json_api_client/linking/top_level_links.rb b/lib/json_api_client/linking/top_level_links.rb index 542d717e..4a1884af 100644 --- a/lib/json_api_client/linking/top_level_links.rb +++ b/lib/json_api_client/linking/top_level_links.rb @@ -31,6 +31,7 @@ def link_url_for(link_name) end def fetch_link(link_name) + return unless respond_to_missing?(link_name) record_class.requestor.linked(link_url_for(link_name)) end end diff --git a/test/unit/top_level_links_test.rb b/test/unit/top_level_links_test.rb index 814737f8..381db836 100644 --- a/test/unit/top_level_links_test.rb +++ b/test/unit/top_level_links_test.rb @@ -74,6 +74,27 @@ def test_can_parse_pagination_links assert_pagination end + def test_can_parse_pagination_links_when_no_next_page + stub_request(:get, "http://example.com/articles") + .to_return(headers: {content_type: "application/vnd.api+json"}, body: { + data: [{ + type: "articles", + id: "1", + attributes: { + title: "JSON API paints my bikeshed!" + } + }], + links: { + self: "http://example.com/articles", + prev: nil, + first: "http://example.com/articles", + last: "http://example.com/articles?page=1" + } + }.to_json) + + assert_pagination_when_no_next_page + end + def test_can_parse_complex_pagination_links stub_request(:get, "http://example.com/articles") .to_return(headers: {content_type: "application/vnd.api+json"}, body: { @@ -179,4 +200,28 @@ def assert_pagination assert_equal "JSON API paints my bikeshed!", article.title end + def assert_pagination_when_no_next_page + articles = Article.all + + # test kaminari pagination params + assert_equal 1, articles.current_page + assert_equal 1, articles.per_page + assert_equal 1, articles.total_pages + assert_equal 0, articles.offset + assert_equal 1, articles.total_entries + assert_equal 1, articles.limit_value + assert_equal nil, articles.next_page + assert_equal 1, articles.per_page + assert_equal false, articles.out_of_bounds? + + # test browsing to next page + pages = articles.pages + assert pages.respond_to?(:next) + assert pages.respond_to?(:prev) + assert pages.respond_to?(:last) + assert pages.respond_to?(:first) + + page2 = articles.pages.next + assert page2.nil? + end end