Skip to content

Commit

Permalink
Merge pull request #88 from cdcooksey/adds_constructor_args
Browse files Browse the repository at this point in the history
Adds accessor settings on instantiation via block or hash.
  • Loading branch information
Phillip Toland committed Mar 10, 2015
2 parents d083da4 + 1a2e32d commit a524d18
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 6 deletions.
23 changes: 17 additions & 6 deletions lib/patron/session.rb
Expand Up @@ -87,12 +87,23 @@ class Session
private :handle_request, :enable_cookie_session, :set_debug_file

# Create a new Session object.
def initialize
@headers = {}
@timeout = 5
@connect_timeout = 1
@max_redirects = 5
@auth_type = :basic
def initialize(args = {}, &block)

# Allows accessors to be set via constructor hash. Ex: {:base_url => 'www.home.com'}
args.each do |attribute, value|
send("#{attribute}=", value)
end

# Allows accessors to be set via block.
if block_given?
yield self
end

@headers ||= {}
@timeout ||= 5
@connect_timeout ||= 1
@max_redirects ||= 5
@auth_type ||= :basic
end

# Turn on cookie handling for this session, storing them in memory by
Expand Down
67 changes: 67 additions & 0 deletions spec/session_spec.rb
Expand Up @@ -322,6 +322,73 @@ def encode_authz(user, passwd)
"Basic " + Base64.encode64("#{user}:#{passwd}").strip
end

describe 'when instantiating with hash arguments' do

let(:args) { {
:timeout => 10,
:base_url => 'http://localhost:9001',
:headers => {'User-Agent' => 'myapp/1.0'}
} }

let(:session) { Patron::Session.new(args) }

it 'sets the base_url' do
session.base_url.should == args[:base_url]
end

it 'sets timeout' do
session.timeout.should == args[:timeout]
end

it 'sets headers' do
session.headers.should == args[:headers]
end

context 'when given an incorrect accessor name' do
let(:args) { { :not_a_real_accessor => 'http://localhost:9001' }}
it 'raises no method error' do
expect { session }.to raise_error NoMethodError
end
end

end

describe 'when instantiating with a block' do
args = {
:timeout => 10,
:base_url => 'http://localhost:9001',
:headers => {'User-Agent' => 'myapp/1.0'}
}

session = Patron::Session.new do |patron|
patron.timeout = args[:timeout]
patron.base_url = args[:base_url]
patron.headers = args[:headers]
end

it 'sets the base_url' do
session.base_url.should == args[:base_url]
end

it 'sets timeout' do
session.timeout.should == args[:timeout]
end

it 'sets headers' do
session.headers.should == args[:headers]
end

context 'when given an incorrect accessor name' do
it 'raises no method error' do
expect {
Patron::Session.new do |patron|
patron.timeoutttt = args[:timeout]
end
}.to raise_error NoMethodError
end
end
end

# ------------------------------------------------------------------------
describe 'when debug is enabled' do
it 'it should not clobber stderr' do
Expand Down

0 comments on commit a524d18

Please sign in to comment.