class Shrine::Storage::AliyunOSS

Attributes

bucket[R]
prefix[R]

Public Class Methods

new(prefix:, **oss_options) click to toggle source
# File lib/shrine/storage/aliyun_oss.rb, line 8
def initialize(prefix:, **oss_options)
  bucket_name = oss_options.delete(:bucket)
  @prefix = prefix
  @client = Aliyun::OSS::Client.new(**oss_options)
  @bucket = @client.get_bucket(bucket_name)
end

Public Instance Methods

delete(id) click to toggle source
# File lib/shrine/storage/aliyun_oss.rb, line 62
def delete(id)
  bucket.delete_object(object_key(id))
end
download(id) click to toggle source

Downloads the file from Aliyun OSS, and returns a `Tempfile`.

# File lib/shrine/storage/aliyun_oss.rb, line 31
def download(id)
  tempfile = Tempfile.new(["shrine-aliyun-oss", File.extname(id)], binmode: true)
  object = bucket.get_object(object_key(id), file: tempfile)

  tempfile.singleton_class.instance_eval { attr_accessor :content_type }
  tempfile.content_type = object.headers[:content_type]
  tempfile.tap(&:open)
rescue
  tempfile.close! if tempfile
  raise
end
exists?(id) click to toggle source
# File lib/shrine/storage/aliyun_oss.rb, line 58
def exists?(id)
  bucket.object_exists?(object_key(id))
end
object_key(id) click to toggle source
# File lib/shrine/storage/aliyun_oss.rb, line 66
def object_key(id)
  prefix ? "#{prefix}/#{id}" : id
end
open(id) click to toggle source
# File lib/shrine/storage/aliyun_oss.rb, line 43
def open(id)
  chunks = nil
  object = bucket.get_object(object_key(id)) do |chunk|
    chunks = Enumerator.new do |y|
      y << chunk
    end
  end

  Down::ChunkedIO.new(
    chunks: chunks,
    size:   object.size,
    data:   { object: object }
  )
end
upload(io, id, shrine_metadata: {}, **upload_options) click to toggle source
# File lib/shrine/storage/aliyun_oss.rb, line 15
def upload(io, id, shrine_metadata: {}, **upload_options)
  content_type = shrine_metadata["mime_type"]

  if copyable?(io)
    bucket.copy_object(io.storage.object_key(io.id), object_key(id))
  else
    # bucket.put_object(object_key(id), content_type: content_type) { |stream| stream << io.read }
    bucket.put_object(object_key(id)) { |stream| stream << io.read }
  end
end
url(id, sign: true, expiry: 900) click to toggle source
# File lib/shrine/storage/aliyun_oss.rb, line 26
def url(id, sign: true, expiry: 900)
  bucket.object_url(object_key(id), sign, expiry)
end

Private Instance Methods

copyable?(io) click to toggle source
# File lib/shrine/storage/aliyun_oss.rb, line 74
def copyable?(io)
  io.is_a?(UploadedFile) &&
  io.storage.is_a?(Storage::AliyunOSS)
end