isaacfeliu-aws-s3 0.4.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,58 @@
1
+ module AWS
2
+ module S3
3
+ # Objects on S3 can be distributed via the BitTorrent file sharing protocol.
4
+ #
5
+ # You can get a torrent file for an object by calling <tt>torrent_for</tt>:
6
+ #
7
+ # S3Object.torrent_for 'kiss.jpg', 'marcel'
8
+ #
9
+ # Or just call the <tt>torrent</tt> method if you already have the object:
10
+ #
11
+ # song = S3Object.find 'kiss.jpg', 'marcel'
12
+ # song.torrent
13
+ #
14
+ # Calling <tt>grant_torrent_access_to</tt> on a object will allow anyone to anonymously
15
+ # fetch the torrent file for that object:
16
+ #
17
+ # S3Object.grant_torrent_access_to 'kiss.jpg', 'marcel'
18
+ #
19
+ # Anonymous requests to
20
+ #
21
+ # http://s3.amazonaws.com/marcel/kiss.jpg?torrent
22
+ #
23
+ # will serve up the torrent file for that object.
24
+ module BitTorrent
25
+ def self.included(klass) #:nodoc:
26
+ klass.extend ClassMethods
27
+ end
28
+
29
+ # Adds methods to S3Object for accessing the torrent of a given object.
30
+ module ClassMethods
31
+ # Returns the torrent file for the object with the given <tt>key</tt>.
32
+ def torrent_for(key, bucket = nil)
33
+ get(path!(bucket, key) << '?torrent').body
34
+ end
35
+ alias_method :torrent, :torrent_for
36
+
37
+ # Grants access to the object with the given <tt>key</tt> to be accessible as a torrent.
38
+ def grant_torrent_access_to(key, bucket = nil)
39
+ policy = acl(key, bucket)
40
+ return true if policy.grants.include?(:public_read)
41
+ policy.grants << ACL::Grant.grant(:public_read)
42
+ acl(key, bucket, policy)
43
+ end
44
+ alias_method :grant_torrent_access, :grant_torrent_access_to
45
+ end
46
+
47
+ # Returns the torrent file for the object.
48
+ def torrent
49
+ self.class.torrent_for(key, bucket.name)
50
+ end
51
+
52
+ # Grants torrent access publicly to anyone who requests it on this object.
53
+ def grant_torrent_access
54
+ self.class.grant_torrent_access_to(key, bucket.name)
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,320 @@
1
+ module AWS
2
+ module S3
3
+ # Buckets are containers for objects (the files you store on S3). To create a new bucket you just specify its name.
4
+ #
5
+ # # Pick a unique name, or else you'll get an error
6
+ # # if the name is already taken.
7
+ # Bucket.create('jukebox')
8
+ #
9
+ # Bucket names must be unique across the entire S3 system, sort of like domain names across the internet. If you try
10
+ # to create a bucket with a name that is already taken, you will get an error.
11
+ #
12
+ # Assuming the name you chose isn't already taken, your new bucket will now appear in the bucket list:
13
+ #
14
+ # Service.buckets
15
+ # # => [#<AWS::S3::Bucket @attributes={"name"=>"jukebox"}>]
16
+ #
17
+ # Once you have succesfully created a bucket you can you can fetch it by name using Bucket.find.
18
+ #
19
+ # music_bucket = Bucket.find('jukebox')
20
+ #
21
+ # The bucket that is returned will contain a listing of all the objects in the bucket.
22
+ #
23
+ # music_bucket.objects.size
24
+ # # => 0
25
+ #
26
+ # If all you are interested in is the objects of the bucket, you can get to them directly using Bucket.objects.
27
+ #
28
+ # Bucket.objects('jukebox').size
29
+ # # => 0
30
+ #
31
+ # By default all objects will be returned, though there are several options you can use to limit what is returned, such as
32
+ # specifying that only objects whose name is after a certain place in the alphabet be returned, and etc. Details about these options can
33
+ # be found in the documentation for Bucket.find.
34
+ #
35
+ # To add an object to a bucket you specify the name of the object, its value, and the bucket to put it in.
36
+ #
37
+ # file = 'black-flowers.mp3'
38
+ # S3Object.store(file, open(file), 'jukebox')
39
+ #
40
+ # You'll see your file has been added to it:
41
+ #
42
+ # music_bucket.objects
43
+ # # => [#<AWS::S3::S3Object '/jukebox/black-flowers.mp3'>]
44
+ #
45
+ # You can treat your bucket like a hash and access objects by name:
46
+ #
47
+ # jukebox['black-flowers.mp3']
48
+ # # => #<AWS::S3::S3Object '/jukebox/black-flowers.mp3'>
49
+ #
50
+ # In the event that you want to delete a bucket, you can use Bucket.delete.
51
+ #
52
+ # Bucket.delete('jukebox')
53
+ #
54
+ # Keep in mind, like unix directories, you can not delete a bucket unless it is empty. Trying to delete a bucket
55
+ # that contains objects will raise a BucketNotEmpty exception.
56
+ #
57
+ # Passing the :force => true option to delete will take care of deleting all the bucket's objects for you.
58
+ #
59
+ # Bucket.delete('photos', :force => true)
60
+ # # => true
61
+ class Bucket < Base
62
+ class << self
63
+ # Creates a bucket named <tt>name</tt>.
64
+ #
65
+ # Bucket.create('jukebox')
66
+ #
67
+ # Your bucket name must be unique across all of S3. If the name
68
+ # you request has already been taken, you will get a 409 Conflict response, and a BucketAlreadyExists exception
69
+ # will be raised.
70
+ #
71
+ # By default new buckets have their access level set to private. You can override this using the <tt>:access</tt> option.
72
+ #
73
+ # Bucket.create('internet_drop_box', :access => :public_read_write)
74
+ #
75
+ # The full list of access levels that you can set on Bucket and S3Object creation are listed in the README[link:files/README.html]
76
+ # in the section called 'Setting access levels'.
77
+ def create(name, options = {})
78
+ validate_name!(name)
79
+ put("/#{name}", options).success?
80
+ end
81
+
82
+ # Fetches the bucket named <tt>name</tt>.
83
+ #
84
+ # Bucket.find('jukebox')
85
+ #
86
+ # If a default bucket is inferable from the current connection's subdomain, or if set explicitly with Base.set_current_bucket,
87
+ # it will be used if no bucket is specified.
88
+ #
89
+ # MusicBucket.current_bucket
90
+ # => 'jukebox'
91
+ # MusicBucket.find.name
92
+ # => 'jukebox'
93
+ #
94
+ # By default all objects contained in the bucket will be returned (sans their data) along with the bucket.
95
+ # You can access your objects using the Bucket#objects method.
96
+ #
97
+ # Bucket.find('jukebox').objects
98
+ #
99
+ # There are several options which allow you to limit which objects are retrieved. The list of object filtering options
100
+ # are listed in the documentation for Bucket.objects.
101
+ def find(name = nil, options = {})
102
+ new(get(path(name, options)).bucket)
103
+ end
104
+
105
+ # Return just the objects in the bucket named <tt>name</tt>.
106
+ #
107
+ # By default all objects of the named bucket will be returned. There are options, though, for filtering
108
+ # which objects are returned.
109
+ #
110
+ # === Object filtering options
111
+ #
112
+ # * <tt>:max_keys</tt> - The maximum number of keys you'd like to see in the response body.
113
+ # The server may return fewer than this many keys, but will not return more.
114
+ #
115
+ # Bucket.objects('jukebox').size
116
+ # # => 3
117
+ # Bucket.objects('jukebox', :max_keys => 1).size
118
+ # # => 1
119
+ #
120
+ # * <tt>:prefix</tt> - Restricts the response to only contain results that begin with the specified prefix.
121
+ #
122
+ # Bucket.objects('jukebox')
123
+ # # => [<AWS::S3::S3Object '/jazz/miles.mp3'>, <AWS::S3::S3Object '/jazz/dolphy.mp3'>, <AWS::S3::S3Object '/classical/malher.mp3'>]
124
+ # Bucket.objects('jukebox', :prefix => 'classical')
125
+ # # => [<AWS::S3::S3Object '/classical/malher.mp3'>]
126
+ #
127
+ # * <tt>:marker</tt> - Marker specifies where in the result set to resume listing. It restricts the response
128
+ # to only contain results that occur alphabetically _after_ the value of marker. To retrieve the next set of results,
129
+ # use the last key from the current page of results as the marker in your next request.
130
+ #
131
+ # # Skip 'mahler'
132
+ # Bucket.objects('jukebox', :marker => 'mb')
133
+ # # => [<AWS::S3::S3Object '/jazz/miles.mp3'>]
134
+ #
135
+ # === Examples
136
+ #
137
+ # # Return no more than 2 objects whose key's are listed alphabetically after the letter 'm'.
138
+ # Bucket.objects('jukebox', :marker => 'm', :max_keys => 2)
139
+ # # => [<AWS::S3::S3Object '/jazz/miles.mp3'>, <AWS::S3::S3Object '/classical/malher.mp3'>]
140
+ #
141
+ # # Return no more than 2 objects whose key's are listed alphabetically after the letter 'm' and have the 'jazz' prefix.
142
+ # Bucket.objects('jukebox', :marker => 'm', :max_keys => 2, :prefix => 'jazz')
143
+ # # => [<AWS::S3::S3Object '/jazz/miles.mp3'>]
144
+ def objects(name = nil, options = {})
145
+ find(name, options).object_cache
146
+ end
147
+
148
+ # Deletes the bucket named <tt>name</tt>.
149
+ #
150
+ # All objects in the bucket must be deleted before the bucket can be deleted. If the bucket is not empty,
151
+ # BucketNotEmpty will be raised.
152
+ #
153
+ # You can side step this issue by passing the :force => true option to delete which will take care of
154
+ # emptying the bucket before deleting it.
155
+ #
156
+ # Bucket.delete('photos', :force => true)
157
+ #
158
+ # Only the owner of a bucket can delete a bucket, regardless of the bucket's access control policy.
159
+ def delete(name = nil, options = {})
160
+ name = path(name)
161
+ find(name).delete_all if options[:force]
162
+ # A bit confusing. Calling super actually makes makes an HTTP DELETE request. The delete method is
163
+ # defined in the Base class. It happens to have the same name.
164
+ super(name).success?
165
+ end
166
+
167
+ # List all your buckets. This is a convenient wrapper around AWS::S3::Service.buckets.
168
+ def list(reload = false)
169
+ Service.buckets(reload)
170
+ end
171
+
172
+ private
173
+ def validate_name!(name)
174
+ raise InvalidBucketName.new(name) unless name =~ /^[-\w.]{3,255}$/
175
+ end
176
+
177
+ def path(name, options = {})
178
+ if name.is_a?(Hash)
179
+ options = name
180
+ name = nil
181
+ end
182
+ "/#{bucket_name(name)}#{RequestOptions.process(options).to_query_string}"
183
+ end
184
+ end
185
+
186
+ attr_reader :object_cache #:nodoc:
187
+
188
+ include Enumerable
189
+
190
+ def initialize(attributes = {}) #:nodoc:
191
+ super
192
+ @object_cache = []
193
+ build_contents!
194
+ end
195
+
196
+ # Fetches the object named <tt>object_key</tt>, or nil if the bucket does not contain an object with the
197
+ # specified key.
198
+ #
199
+ # bucket.objects
200
+ # => [#<AWS::S3::S3Object '/marcel_molina/beluga_baby.jpg'>,
201
+ # #<AWS::S3::S3Object '/marcel_molina/tongue_overload.jpg'>]
202
+ # bucket['beluga_baby.jpg']
203
+ # => #<AWS::S3::S3Object '/marcel_molina/beluga_baby.jpg'>
204
+ def [](object_key)
205
+ detect {|file| file.key == object_key.to_s}
206
+ end
207
+
208
+ # Initializes a new S3Object belonging to the current bucket.
209
+ #
210
+ # object = bucket.new_object
211
+ # object.value = data
212
+ # object.key = 'classical/mahler.mp3'
213
+ # object.store
214
+ # bucket.objects.include?(object)
215
+ # => true
216
+ def new_object(attributes = {})
217
+ object = S3Object.new(attributes)
218
+ register(object)
219
+ object
220
+ end
221
+
222
+ # List S3Object's of the bucket.
223
+ #
224
+ # Once fetched the objects will be cached. You can reload the objects by passing <tt>:reload</tt>.
225
+ #
226
+ # bucket.objects(:reload)
227
+ #
228
+ # You can also filter the objects using the same options listed in Bucket.objects.
229
+ #
230
+ # bucket.objects(:prefix => 'jazz')
231
+ #
232
+ # Using these filtering options will implictly reload the objects.
233
+ #
234
+ # To reclaim all the objects for the bucket you can pass in :reload again.
235
+ def objects(options = {})
236
+ if options.is_a?(Hash)
237
+ reload = !options.empty?
238
+ else
239
+ reload = options
240
+ options = {}
241
+ end
242
+
243
+ reload!(options) if reload || object_cache.empty?
244
+ object_cache
245
+ end
246
+
247
+ # Iterates over the objects in the bucket.
248
+ #
249
+ # bucket.each do |object|
250
+ # # Do something with the object ...
251
+ # end
252
+ def each(&block)
253
+ # Dup the collection since we might be destructively modifying the object_cache during the iteration.
254
+ objects.dup.each(&block)
255
+ end
256
+
257
+ # Returns true if there are no objects in the bucket.
258
+ def empty?
259
+ objects.empty?
260
+ end
261
+
262
+ # Returns the number of objects in the bucket.
263
+ def size
264
+ objects.size
265
+ end
266
+
267
+ # Deletes the bucket. See its class method counter part Bucket.delete for caveats about bucket deletion and how to ensure
268
+ # a bucket is deleted no matter what.
269
+ def delete(options = {})
270
+ self.class.delete(name, options)
271
+ end
272
+
273
+ # Delete all files in the bucket. Use with caution. Can not be undone.
274
+ def delete_all
275
+ each do |object|
276
+ object.delete
277
+ end
278
+ self
279
+ end
280
+ alias_method :clear, :delete_all
281
+
282
+ # Buckets observe their objects and have this method called when one of their objects
283
+ # is either stored or deleted.
284
+ def update(action, object) #:nodoc:
285
+ case action
286
+ when :stored then add object unless objects.include?(object)
287
+ when :deleted then object_cache.delete(object)
288
+ end
289
+ end
290
+
291
+ private
292
+ def build_contents!
293
+ return unless has_contents?
294
+ attributes.delete('contents').each do |content|
295
+ add new_object(content)
296
+ end
297
+ end
298
+
299
+ def has_contents?
300
+ attributes.has_key?('contents')
301
+ end
302
+
303
+ def add(object)
304
+ register(object)
305
+ object_cache << object
306
+ end
307
+
308
+ def register(object)
309
+ object.bucket = self
310
+ end
311
+
312
+ def reload!(options = {})
313
+ object_cache.clear
314
+ self.class.objects(name, options).each do |object|
315
+ add object
316
+ end
317
+ end
318
+ end
319
+ end
320
+ end
@@ -0,0 +1,320 @@
1
+ module AWS
2
+ module S3
3
+ class Connection #:nodoc:
4
+ class << self
5
+ def connect(options = {})
6
+ new(options)
7
+ end
8
+
9
+ def prepare_path(path)
10
+ path = path.remove_extended unless path.utf8?
11
+ URI.escape(path)
12
+ end
13
+ end
14
+
15
+ attr_reader :access_key_id, :secret_access_key, :http, :options
16
+
17
+ # Creates a new connection. Connections make the actual requests to S3, though these requests are usually
18
+ # called from subclasses of Base.
19
+ #
20
+ # For details on establishing connections, check the Connection::Management::ClassMethods.
21
+ def initialize(options = {})
22
+ @options = Options.new(options)
23
+ connect
24
+ end
25
+
26
+ def request(verb, path, headers = {}, body = nil, attempts = 0, &block)
27
+ body.rewind if body.respond_to?(:rewind) unless attempts.zero?
28
+
29
+ requester = Proc.new do
30
+ path = self.class.prepare_path(path)
31
+ request = request_method(verb).new(path, headers)
32
+ ensure_content_type!(request)
33
+ add_user_agent!(request)
34
+ set_host!(request)
35
+ authenticate!(request)
36
+ if body
37
+ if body.respond_to?(:read)
38
+ request.body_stream = body
39
+ request.content_length = body.respond_to?(:lstat) ? body.lstat.size : body.size
40
+ else
41
+ request.body = body
42
+ end
43
+ end
44
+ http.request(request, &block)
45
+ end
46
+
47
+ if persistent?
48
+ http.start unless http.started?
49
+ requester.call
50
+ else
51
+ http.start(&requester)
52
+ end
53
+ rescue Errno::EPIPE, Timeout::Error, Errno::EPIPE, Errno::EINVAL
54
+ @http = create_connection
55
+ attempts == 3 ? raise : (attempts += 1; retry)
56
+ end
57
+
58
+ def url_for(path, options = {})
59
+ authenticate = options.delete(:authenticated)
60
+ # Default to true unless explicitly false
61
+ authenticate = true if authenticate.nil?
62
+ path = self.class.prepare_path(path)
63
+ request = request_method(:get).new(path, {})
64
+ query_string = query_string_authentication(request, options)
65
+ returning "#{protocol(options)}#{http.address}#{port_string}#{path}" do |url|
66
+ url << "?#{query_string}" if authenticate
67
+ end
68
+ end
69
+
70
+ def subdomain
71
+ subdomain = http.address.gsub("#{DEFAULT_HOST}", "").gsub(/.$/,'')
72
+ subdomain.empty? ? nil : subdomain
73
+ end
74
+
75
+ def persistent?
76
+ options[:persistent]
77
+ end
78
+
79
+ def protocol(options = {})
80
+ (options[:use_ssl] || http.use_ssl?) ? 'https://' : 'http://'
81
+ end
82
+
83
+ private
84
+ def extract_keys!
85
+ missing_keys = []
86
+ extract_key = Proc.new {|key| options[key] || (missing_keys.push(key); nil)}
87
+ @access_key_id = extract_key[:access_key_id]
88
+ @secret_access_key = extract_key[:secret_access_key]
89
+ raise MissingAccessKey.new(missing_keys) unless missing_keys.empty?
90
+ end
91
+
92
+ def create_connection
93
+ http = http_class.new(options[:server], options[:port])
94
+ http.use_ssl = !options[:use_ssl].nil? || options[:port] == 443
95
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
96
+ http
97
+ end
98
+
99
+ def http_class
100
+ if options.connecting_through_proxy?
101
+ Net::HTTP::Proxy(*options.proxy_settings)
102
+ else
103
+ Net::HTTP
104
+ end
105
+ end
106
+
107
+ def connect
108
+ extract_keys!
109
+ @http = create_connection
110
+ end
111
+
112
+ def port_string
113
+ default_port = options[:use_ssl] ? 443 : 80
114
+ http.port == default_port ? '' : ":#{http.port}"
115
+ end
116
+
117
+ def ensure_content_type!(request)
118
+ request['Content-Type'] ||= 'binary/octet-stream'
119
+ end
120
+
121
+ # Just do Header authentication for now
122
+ def authenticate!(request)
123
+ request['Authorization'] = Authentication::Header.new(request, access_key_id, secret_access_key)
124
+ end
125
+
126
+ def add_user_agent!(request)
127
+ request['User-Agent'] ||= "AWS::S3/#{Version}"
128
+ end
129
+
130
+ def set_host!(request)
131
+ request['Host'] = http.address
132
+ end
133
+
134
+ def query_string_authentication(request, options = {})
135
+ Authentication::QueryString.new(request, access_key_id, secret_access_key, options)
136
+ end
137
+
138
+ def request_method(verb)
139
+ Net::HTTP.const_get(verb.to_s.capitalize)
140
+ end
141
+
142
+ def method_missing(method, *args, &block)
143
+ options[method] || super
144
+ end
145
+
146
+ module Management #:nodoc:
147
+ def self.included(base)
148
+ base.cattr_accessor :connections
149
+ base.connections = {}
150
+ base.extend ClassMethods
151
+ end
152
+
153
+ # Manage the creation and destruction of connections for AWS::S3::Base and its subclasses. Connections are
154
+ # created with establish_connection!.
155
+ module ClassMethods
156
+ # Creates a new connection with which to make requests to the S3 servers for the calling class.
157
+ #
158
+ # AWS::S3::Base.establish_connection!(:access_key_id => '...', :secret_access_key => '...')
159
+ #
160
+ # You can set connections for every subclass of AWS::S3::Base. Once the initial connection is made on
161
+ # Base, all subsequent connections will inherit whatever values you don't specify explictly. This allows you to
162
+ # customize details of the connection, such as what server the requests are made to, by just specifying one
163
+ # option.
164
+ #
165
+ # AWS::S3::Bucket.established_connection!(:use_ssl => true)
166
+ #
167
+ # The Bucket connection would inherit the <tt>:access_key_id</tt> and the <tt>:secret_access_key</tt> from
168
+ # Base's connection. Unlike the Base connection, all Bucket requests would be made over SSL.
169
+ #
170
+ # == Required arguments
171
+ #
172
+ # * <tt>:access_key_id</tt> - The access key id for your S3 account. Provided by Amazon.
173
+ # * <tt>:secret_access_key</tt> - The secret access key for your S3 account. Provided by Amazon.
174
+ #
175
+ # If any of these required arguments is missing, a MissingAccessKey exception will be raised.
176
+ #
177
+ # == Optional arguments
178
+ #
179
+ # * <tt>:server</tt> - The server to make requests to. You can use this to specify your bucket in the subdomain,
180
+ # or your own domain's cname if you are using virtual hosted buckets. Defaults to <tt>s3.amazonaws.com</tt>.
181
+ # * <tt>:port</tt> - The port to the requests should be made on. Defaults to 80 or 443 if the <tt>:use_ssl</tt>
182
+ # argument is set.
183
+ # * <tt>:use_ssl</tt> - Whether requests should be made over SSL. If set to true, the <tt>:port</tt> argument
184
+ # will be implicitly set to 443, unless specified otherwise. Defaults to false.
185
+ # * <tt>:persistent</tt> - Whether to use a persistent connection to the server. Having this on provides around a two fold
186
+ # performance increase but for long running processes some firewalls may find the long lived connection suspicious and close the connection.
187
+ # If you run into connection errors, try setting <tt>:persistent</tt> to false. Defaults to true.
188
+ # * <tt>:proxy</tt> - If you need to connect through a proxy, you can specify your proxy settings by specifying a <tt>:host</tt>, <tt>:port</tt>, <tt>:user</tt>, and <tt>:password</tt>
189
+ # with the <tt>:proxy</tt> option.
190
+ # The <tt>:host</tt> setting is required if specifying a <tt>:proxy</tt>.
191
+ #
192
+ # AWS::S3::Bucket.established_connection!(:proxy => {
193
+ # :host => '...', :port => 8080, :user => 'marcel', :password => 'secret'
194
+ # })
195
+ def establish_connection!(options = {})
196
+ # After you've already established the default connection, just specify
197
+ # the difference for subsequent connections
198
+ options = default_connection.options.merge(options) if connected?
199
+ connections[connection_name] = Connection.connect(options)
200
+ end
201
+
202
+ # Returns the connection for the current class, or Base's default connection if the current class does not
203
+ # have its own connection.
204
+ #
205
+ # If not connection has been established yet, NoConnectionEstablished will be raised.
206
+ def connection
207
+ if connected?
208
+ connections[connection_name] || default_connection
209
+ else
210
+ raise NoConnectionEstablished
211
+ end
212
+ end
213
+
214
+ # Returns true if a connection has been made yet.
215
+ def connected?
216
+ !connections.empty?
217
+ end
218
+
219
+ # Removes the connection for the current class. If there is no connection for the current class, the default
220
+ # connection will be removed.
221
+ def disconnect(name = connection_name)
222
+ name = default_connection unless connections.has_key?(name)
223
+ connection = connections[name]
224
+ connection.http.finish if connection.persistent?
225
+ connections.delete(name)
226
+ end
227
+
228
+ # Clears *all* connections, from all classes, with prejudice.
229
+ def disconnect!
230
+ connections.each_key {|connection| disconnect(connection)}
231
+ end
232
+
233
+ private
234
+ def connection_name
235
+ name
236
+ end
237
+
238
+ def default_connection_name
239
+ 'AWS::S3::Base'
240
+ end
241
+
242
+ def default_connection
243
+ connections[default_connection_name]
244
+ end
245
+ end
246
+ end
247
+
248
+ class Options < Hash #:nodoc:
249
+ class << self
250
+ def valid_options
251
+ [:access_key_id, :secret_access_key, :server, :port, :use_ssl, :persistent, :proxy]
252
+ end
253
+ end
254
+
255
+ attr_reader :options
256
+ def initialize(options = {})
257
+ super()
258
+ @options = options
259
+ validate!
260
+ extract_proxy_settings!
261
+ extract_persistent!
262
+ extract_server!
263
+ extract_port!
264
+ extract_remainder!
265
+ end
266
+
267
+ def connecting_through_proxy?
268
+ !self[:proxy].nil?
269
+ end
270
+
271
+ def proxy_settings
272
+ proxy_setting_keys.map do |proxy_key|
273
+ self[:proxy][proxy_key]
274
+ end
275
+ end
276
+
277
+ private
278
+ def proxy_setting_keys
279
+ [:host, :port, :user, :password]
280
+ end
281
+
282
+ def missing_proxy_settings?
283
+ !self[:proxy].keys.include?(:host)
284
+ end
285
+
286
+ def extract_persistent!
287
+ self[:persistent] = options.has_key?(:persitent) ? options[:persitent] : true
288
+ end
289
+
290
+ def extract_proxy_settings!
291
+ self[:proxy] = options.delete(:proxy) if options.include?(:proxy)
292
+ validate_proxy_settings!
293
+ end
294
+
295
+ def extract_server!
296
+ self[:server] = options.delete(:server) || DEFAULT_HOST
297
+ end
298
+
299
+ def extract_port!
300
+ self[:port] = options.delete(:port) || (options[:use_ssl] ? 443 : 80)
301
+ end
302
+
303
+ def extract_remainder!
304
+ update(options)
305
+ end
306
+
307
+ def validate!
308
+ invalid_options = options.keys.select {|key| !self.class.valid_options.include?(key)}
309
+ raise InvalidConnectionOption.new(invalid_options) unless invalid_options.empty?
310
+ end
311
+
312
+ def validate_proxy_settings!
313
+ if connecting_through_proxy? && missing_proxy_settings?
314
+ raise ArgumentError, "Missing proxy settings. Must specify at least :host."
315
+ end
316
+ end
317
+ end
318
+ end
319
+ end
320
+ end