Class: Dato::Upload::CreateUploadPath

Inherits:
Object
  • Object
show all
Defined in:
lib/dato/upload/create_upload_path.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, source) ⇒ CreateUploadPath

Returns a new instance of CreateUploadPath.



13
14
15
16
# File 'lib/dato/upload/create_upload_path.rb', line 13

def initialize(client, source)
  @client = client
  @source = source
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



11
12
13
# File 'lib/dato/upload/create_upload_path.rb', line 11

def client
  @client
end

#sourceObject (readonly)

Returns the value of attribute source.



11
12
13
# File 'lib/dato/upload/create_upload_path.rb', line 11

def source
  @source
end

Instance Method Details

#download_file(url) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
# File 'lib/dato/upload/create_upload_path.rb', line 65

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

#fileObject



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/dato/upload/create_upload_path.rb', line 18

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

#filenameObject



39
40
41
42
43
44
45
# File 'lib/dato/upload/create_upload_path.rb', line 39

def filename
  if http_source?
    ::File.basename(source)
  else
    ::File.basename(file.path)
  end
end

#http_source?Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
# File 'lib/dato/upload/create_upload_path.rb', line 32

def http_source?
  uri = Addressable::URI.parse(source)
  uri.scheme == "http" || uri.scheme == "https"
rescue Addressable::URI::InvalidURIError
  false
end

#upload_pathObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/dato/upload/create_upload_path.rb', line 47

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