Make Docs:Requester#request accept an array of URLs

pull/29/head
Thibaut 11 years ago
parent 562a4c74fe
commit c6be9b6ae4

@ -4,10 +4,10 @@ module Docs
class Requester < Typhoeus::Hydra
attr_reader :request_options
def self.run(url, options = {}, &block)
def self.run(urls, options = {}, &block)
requester = new(options)
requester.on_response(&block) if block
requester.request(url)
requester.request(urls)
requester.run
requester
end
@ -18,11 +18,11 @@ module Docs
super
end
def request(url, options = {}, &block)
request = Request.new(url, request_options.merge(options))
request.on_complete(&block) if block
queue(request)
request
def request(urls, options = {}, &block)
requests = [urls].flatten.map do |url|
build_and_queue_request(url, options, &block)
end
requests.length == 1 ? requests.first : requests
end
def queue(request)
@ -38,6 +38,13 @@ module Docs
private
def build_and_queue_request(url, options, &block)
request = Request.new(url, request_options.merge(options))
request.on_complete(&block) if block
queue(request)
request
end
def handle_response(response)
on_response.each do |callback|
result = callback.call(response)

@ -10,12 +10,16 @@ class DocsRequesterTest < MiniTest::Spec
Docs::Requester.new(options)
end
let :url do
'http://example.com'
end
let :options do
Hash.new
end
let :url do
'http://example.com'
let :block do
Proc.new {}
end
after do
@ -36,6 +40,7 @@ class DocsRequesterTest < MiniTest::Spec
end
describe "#request" do
context "with a url" do
it "returns a request" do
assert_instance_of Docs::Request, requester.request(url)
end
@ -64,22 +69,45 @@ class DocsRequesterTest < MiniTest::Spec
end
it "has the given block as an on_complete callback" do
block = Proc.new {}
request = requester.request(url, &block)
assert_includes request.on_complete, block
end
end
end
context "with an array of urls" do
let :urls do
['one', 'two']
end
it "returns an array of requests" do
result = requester.request(urls, { params: 'test' }, &block)
assert_instance_of Array, result
assert_equal urls.length, result.length
assert result.all? { |obj| obj.instance_of? Docs::Request }
urls.each_with_index do |url, i|
assert_equal url, result[i].base_url
assert_equal 'test', result[i].options[:params]
assert_includes result[i].on_complete, block
end
end
it "queues the requests in the given order" do
queue = []
stub(requester).queue { |request| queue << request }
assert_equal urls, requester.request(urls).map(&:base_url)
end
end
end
describe "#on_response" do
it "returns an array" do
assert_instance_of Array, requester.on_response
end
it "stores a callback" do
proc = Proc.new {}
requester.on_response(&proc)
assert_includes requester.on_response, proc
requester.on_response(&block)
assert_includes requester.on_response, block
end
end

Loading…
Cancel
Save