Skip to content

Commit 561e18e

Browse files
committed
Merge pull request #52 from no-reply/feature/follow-redirects
Follow redirects when querying sparql. Thanks!
2 parents 2d7f1ac + bc9ad1c commit 561e18e

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

lib/sparql/client.rb

+8-4
Original file line numberDiff line numberDiff line change
@@ -675,11 +675,15 @@ def request(query, headers = {}, &block)
675675
request.basic_auth(url.user, url.password) if url.user && !url.user.empty?
676676

677677
response = @http.request(url, request)
678-
if block_given?
679-
block.call(response)
680-
else
681-
response
678+
679+
10.times do
680+
if response.kind_of? Net::HTTPRedirection
681+
response = @http.request(RDF::URI(response['location']), request)
682+
else
683+
return block_given? ? block.call(response) : response
684+
end
682685
end
686+
raise ServerError, "Infinite redirect at #{url}. Redirected more than 10 times."
683687
end
684688

685689
##

spec/client_spec.rb

+21
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,27 @@ def response(header)
101101
expect(result[:name].to_s).to eq "東京"
102102
end
103103

104+
context "Redirects" do
105+
before do
106+
WebMock.stub_request(:any, 'http://data.linkedmdb.org/sparql').
107+
to_return(:body => '{}', :status => 303, :headers => { 'Location' => 'http://sparql.linkedmdb.org/sparql' })
108+
end
109+
110+
it 'follows redirects' do
111+
WebMock.stub_request(:any, 'http://sparql.linkedmdb.org/sparql').
112+
to_return(:body => '{}', :status => 200)
113+
subject.query(ask_query)
114+
expect(WebMock).to have_requested(:post, "http://sparql.linkedmdb.org/sparql").
115+
with(:body => 'query=ASK+WHERE+%7B+%3Fkb+%3Chttp%3A%2F%2Fdata.linkedmdb.org%2Fresource%2Fmovie%2Factor_name%3E+%22Kevin+Bacon%22+.+%7D')
116+
end
117+
118+
it 'raises an error on infinate redirects' do
119+
WebMock.stub_request(:any, 'http://sparql.linkedmdb.org/sparql').
120+
to_return(:body => '{}', :status => 303, :headers => { 'Location' => 'http://sparql.linkedmdb.org/sparql' })
121+
expect{ subject.query(ask_query) }.to raise_error SPARQL::Client::ServerError
122+
end
123+
end
124+
104125
context "Accept Header" do
105126
it "should use application/sparql-results+json for ASK" do
106127
WebMock.stub_request(:any, 'http://data.linkedmdb.org/sparql').

0 commit comments

Comments
 (0)