lib/ridley/connection.rb in ridley-0.7.0.rc1 vs lib/ridley/connection.rb in ridley-0.7.0.rc3
- old
+ new
@@ -1,5 +1,8 @@
+require 'open-uri'
+require 'tempfile'
+
module Ridley
# @author Jamie Winsor <jamie@vialstudios.com>
class Connection < Faraday::Connection
include Celluloid
@@ -13,13 +16,13 @@
attr_reader :organization
attr_reader :client_key
attr_reader :client_name
- # @param [String] :server_url
- # @param [String] :client_name
- # @param [String] :client_key
+ # @param [String] server_url
+ # @param [String] client_name
+ # @param [String] client_key
#
# @option options [Hash] :params
# URI query unencoded key/value pairs
# @option options [Hash] :headers
# unencoded HTTP header key/value pairs
@@ -75,10 +78,54 @@
# @return [Boolean]
def foss?
api_type == :foss
end
+ # Override Faraday::Connection#run_request to catch exceptions from {Ridley::Middleware} that
+ # we expect. Caught exceptions are re-raised with Celluloid#abort so we don't crash the connection.
+ def run_request(*args)
+ super
+ rescue Errors::HTTPError => ex
+ abort(ex)
+ end
+
def server_url
self.url_prefix.to_s
+ end
+
+ # Stream the response body of a remote URL to a file on the local file system
+ #
+ # @param [String] target
+ # a URL to stream the response body from
+ # @param [String] destination
+ # a location on disk to stream the content of the response body to
+ def stream(target, destination)
+ FileUtils.mkdir_p(File.dirname(destination))
+
+ target = Addressable::URI.parse(target)
+ headers = Middleware::ChefAuth.authentication_headers(
+ client_name,
+ client_key,
+ http_method: "GET",
+ host: target.host,
+ path: target.path
+ )
+
+ unless ssl[:verify]
+ headers.merge!(ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE)
+ end
+
+ local = Tempfile.new('ridley-stream')
+ local.binmode
+
+ open(target, 'rb', headers) do |remote|
+ local.write(remote.read)
+ end
+
+ FileUtils.mv(local.path, destination)
+ rescue OpenURI::HTTPError => ex
+ abort(ex)
+ ensure
+ local.close(true) unless local.nil?
end
end
end