From 2c1ec07061d8b7e0830dd380b8fa1f1ea4db32ef Mon Sep 17 00:00:00 2001 From: Marc-Andre Giroux Date: Tue, 11 Feb 2020 14:38:37 -0500 Subject: [PATCH] Handle relation types with dashes and URLs --- lib/sawyer/response.rb | 4 ++-- test/response_test.rb | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/lib/sawyer/response.rb b/lib/sawyer/response.rb index 684aca1..cbd7d4d 100644 --- a/lib/sawyer/response.rb +++ b/lib/sawyer/response.rb @@ -24,7 +24,7 @@ def initialize(agent, res, options = {}) def data @data ||= begin - return(body) unless (headers[:content_type] =~ /json|msgpack/) + return(body) unless (headers[:content_type] =~ /json|msgpack/) process_data(agent.decode_body(body)) end end @@ -49,7 +49,7 @@ def process_data(data) # Returns an array of Relations def process_rels links = ( @headers["Link"] || "" ).split(', ').map do |link| - href, name = link.match(/<(.*?)>; rel="(\w+)"/).captures + href, name = link.match(/<(.*?)>; rel="(.+?)"/).captures [name.to_sym, Relation.from_link(@agent, name, :href => href)] end diff --git a/test/response_test.rb b/test/response_test.rb index 60ef530..5beaeb0 100644 --- a/test/response_test.rb +++ b/test/response_test.rb @@ -24,6 +24,17 @@ def setup emails = %w(rick@example.com technoweenie@example.com) [200, {'Content-Type' => 'application/json'}, Sawyer::Agent.encode(emails)] end + + stub.get '/link_relations' do + [ + 200, + { + 'Content-Type' => 'application/json', + 'Link' => '; rel="next", ; rel="last", ; rel="with-dashes"; type="type="text/html", ; rel="http://example.net/foo"' + }, + {} + ] + end end end @@ -81,6 +92,12 @@ def test_handles_arrays_of_strings res = @agent.call(:get, '/emails') assert_equal 'rick@example.com', res.data.first end + + def test_link_relations + res = @agent.call(:get, '/link_relations') + + assert_equal "/", res.rels[:"http://example.net/foo"].href + assert_equal "/blog_post", res.rels[:"with-dashes"].href + end end end -