Sha256: 9998ccefcf9920d7222c0f407d0ec000226e6d6e60b172d2b811a73ca72058b2
Contents?: true
Size: 1.95 KB
Versions: 3
Compression:
Stored size: 1.95 KB
Contents
# frozen_string_literal: true require "mime/types" require "tempfile" require "addressable" require "net/http" module Dato module Upload class CreateUploadPath attr_reader :client, :source def initialize(client, source) @client = client @source = source end def file @file ||= if http_source? uri = Addressable::URI.parse(source) ext = ::File.extname(uri.path).downcase tempfile = Tempfile.new(["file", ext]) tempfile.binmode tempfile.write(download_file(source)) tempfile.rewind tempfile else ::File.new(::File.expand_path(source)) end end def http_source? uri = Addressable::URI.parse(source) uri.scheme == "http" || uri.scheme == "https" rescue Addressable::URI::InvalidURIError false end def filename if http_source? ::File.basename(source) else ::File.basename(file.path) end end def upload_path upload_request = client.upload_request.create(filename: filename) uri = URI.parse(upload_request[:url]) mime_type = MIME::Types.of(filename).first request = Net::HTTP::Put.new(uri) request.add_field("Content-Type", mime_type.to_s) if mime_type request.body = file.read http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.request(request) upload_request[:id] end def download_file(url) connection = Faraday.new do |c| c.response :raise_error c.use FaradayMiddleware::FollowRedirects c.adapter :net_http end connection.get(url).body rescue Faraday::Error => e puts "Error during upload of #{url}: #{e.message}" raise e end end end end
Version data entries
3 entries across 3 versions & 1 rubygems
Version | Path |
---|---|
dato-0.8.3 | lib/dato/upload/create_upload_path.rb |
dato-0.8.2 | lib/dato/upload/create_upload_path.rb |
dato-0.8.1 | lib/dato/upload/create_upload_path.rb |