Class: Shrine::Storage::Uploadcare

Inherits:
Object
  • Object
show all
Defined in:
lib/shrine/storage/uploadcare.rb

Constant Summary collapse

Error =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ Uploadcare

Returns a new instance of Uploadcare.



14
15
16
# File 'lib/shrine/storage/uploadcare.rb', line 14

def initialize(**options)
  @api = ::Uploadcare::Api.new(**options)
end

Instance Attribute Details

#apiObject (readonly)

Returns the value of attribute api.



12
13
14
# File 'lib/shrine/storage/uploadcare.rb', line 12

def api
  @api
end

Instance Method Details

#clear!Object



70
71
72
73
74
# File 'lib/shrine/storage/uploadcare.rb', line 70

def clear!
  api.file_list(limit: 1000).each_slice(100) do |file_batch|
    api.delete_files(file_batch)
  end
end

#delete(id) ⇒ Object



42
43
44
45
# File 'lib/shrine/storage/uploadcare.rb', line 42

def delete(id)
  file = api.file(id)
  file.delete
end

#exists?(id) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
37
38
39
40
# File 'lib/shrine/storage/uploadcare.rb', line 34

def exists?(id)
  file = api.file(id)
  file.load_data
  !!file.datetime_stored
rescue ::Uploadcare::Error::RequestError::NotFound
  false
end

#open(id, **options) ⇒ Object



28
29
30
31
32
# File 'lib/shrine/storage/uploadcare.rb', line 28

def open(id, **options)
  Down::Http.open(url(id), **options)
rescue Down::NotFound
  raise Shrine::FileNotFound, "file #{id.inspect} not found on storage"
end

#presign(id = nil, **options) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/shrine/storage/uploadcare.rb', line 53

def presign(id = nil, **options)
  expire = Time.now.to_i + (options[:expires_in] || 60*60)
  secret_key = api.options[:private_key]

  signature = Digest::MD5.hexdigest(secret_key + expire.to_s)

  fields = {
    UPLOADCARE_PUB_KEY: api.options[:public_key],
    signature: signature,
    expire: expire,
  }

  url = URI.join(api.options[:upload_url_base], "base/").to_s

  { method: :post, url: url, fields: fields }
end

#upload(io, id, shrine_metadata: {}, **upload_options) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/shrine/storage/uploadcare.rb', line 18

def upload(io, id, shrine_metadata: {}, **upload_options)
  file = _upload(io, id, shrine_metadata: , **upload_options)
  file.load_data

  update_metadata!(, file)
  update_id!(id, file)

  file
end

#url(id, **options) ⇒ Object



47
48
49
50
51
# File 'lib/shrine/storage/uploadcare.rb', line 47

def url(id, **options)
  file = api.file(id)
  file.operations = options.map { |operation| operation.flatten.join("/") }
  file.cdn_url(true)
end