Permalink
Browse files

CurlAgent contructor can receive options now

  • Loading branch information...
1 parent 607a3bc commit f7a1b931290a75c669f53464f9ba74bf3c40cca2 @romanbsd romanbsd committed Mar 3, 2009
Showing with 27 additions and 20 deletions.
  1. +14 −12 lib/curl_agent.rb
  2. +13 −8 spec/curl_agent_spec.rb
View
@@ -3,7 +3,8 @@
require 'curb'
class CurlAgent
- def initialize(url)
+ # See CurlAgent::open for explanation about options
+ def initialize(url, options = {})
@curl = Curl::Easy.new(url)
# Defaults
@curl.headers['User-Agent'] = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6'
@@ -13,6 +14,17 @@ def initialize(url)
@curl.connect_timeout = 5
@curl.timeout = 30
@performed = false
+
+ options ||= {}
+ options.each {|k, v|
+ # Strings will be passed as headers, as in original open-uri
+ next unless k.is_a? Symbol
+ @curl.send("#{k}=".intern, v)
+ options.delete(k)
+ }
+
+ # All that's left should be considered headers
+ @curl.headers.merge!(options)
end
# Do the actual fetch, after which it's possible to call body_str method
@@ -61,17 +73,7 @@ def self.open(name, *rest, &block)
raise ArgumentError.new("invalid access mode #{mode} (resource is read only.)")
end
- agent = CurlAgent.new(name)
-
- options ||= {}
- options.each {|k, v|
- # Strings will be passed as headers, as in original open-uri
- next unless k.is_a? Symbol
- agent.send("#{k}=".intern, v)
- options.delete(k)
- }
- # All that's left should be considered headers
- agent.headers.merge!(options)
+ agent = CurlAgent.new(name, options)
agent.perform!
io = StringIO.new(agent.body_str)
View
@@ -62,21 +62,26 @@
describe 'when used with open' do
before(:each) do
@headers = {'User-Agent'=>'foo'}
- @curl = mock('curl')
- @curl.stub!(:headers).and_return(@headers)
- @curl.stub!(:perform!)
- @curl.stub!(:body_str).and_return('test')
- CurlAgent.should_receive(:new).and_return(@curl)
+ @curl_easy = mock('curl_easy')
+ Curl::Easy.should_receive(:new).and_return(@curl_easy)
+ @curl_easy.stub!(:headers).and_return(@headers)
+ @curl_easy.stub!(:follow_location=)
+ @curl_easy.stub!(:max_redirects=)
+ @curl_easy.stub!(:enable_cookies=)
+ @curl_easy.stub!(:connect_timeout=)
+ @curl_easy.stub!(:timeout=)
+ @curl_easy.stub!(:perform)
+ @curl_easy.stub!(:body_str).and_return('test')
end
it 'shall permit to specify user-agent' do
- @curl.headers['User-Agent'].should_not == 'curl'
+ @curl_easy.headers['User-Agent'].should_not == 'curl'
CurlAgent.open('http://www.example.com/', 'User-Agent'=>'curl')
- @curl.headers['User-Agent'].should == 'curl'
+ @curl_easy.headers['User-Agent'].should == 'curl'
end
it 'shall permit to override timeout' do
- @curl.should_receive(:'timeout=').once.with(10)
+ @curl_easy.should_receive(:'timeout=').once.with(10)
CurlAgent.open('http://www.example.com/', :timeout => 10)
end

0 comments on commit f7a1b93

Please sign in to comment.