lib/tori/backend/s3.rb in tori-0.0.8 vs lib/tori/backend/s3.rb in tori-0.0.9

- old
+ new

@@ -1,10 +1,12 @@ require 'aws-sdk-core' +require 'mime/types' module Tori module Backend class S3 + DEFAULT_CONTENT_TYPE = 'text/plain'.freeze attr_accessor :bucket # Must be set bucket name. # And it use aws-sdk-core >= 2.0 # ENV["TORI_ACCESS_KEY"] > aws-sdk credentials # @@ -15,16 +17,20 @@ @client = nil end def write(filename, resource) case resource - when IO - put filename, f when String - put filename, resource + put_object key: filename, body: resource, content_type: DEFAULT_CONTENT_TYPE + when File, Pathname + path = resource.to_path + content_type = MIME::Types.type_for(path).first || DEFAULT_CONTENT_TYPE + ::File.open(path) { |f| + put_object key: filename, body: f, content_type: content_type.to_s, content_length: f.size + } else - ::File.open(resource.to_path) { |f| put filename, f } + put_object key: filename, body: resource end end def delete(filename) delete_object key: filename @@ -68,24 +74,22 @@ def url_for(filename, method) signer = Aws::S3::Presigner.new(client: client) signer.presigned_url(method, bucket: @bucket, key: filename) end - private - def client @client ||= if ENV["TORI_AWS_ACCESS_KEY_ID"] && ENV["TORI_AWS_SECRET_ACCESS_KEY"] - Aws::S3::Client.new( - access_key_id: ENV["TORI_AWS_ACCESS_KEY_ID"], - secret_access_key: ENV["TORI_AWS_SECRET_ACCESS_KEY"], - region: ENV["TORI_AWS_REGION"] || ENV['AWS_REGION'] || Aws.config[:region], - ) - else - Aws::S3::Client.new( - region: ENV["TORI_AWS_REGION"] || ENV['AWS_REGION'] || Aws.config[:region] - ) - end + Aws::S3::Client.new( + access_key_id: ENV["TORI_AWS_ACCESS_KEY_ID"], + secret_access_key: ENV["TORI_AWS_SECRET_ACCESS_KEY"], + region: ENV["TORI_AWS_REGION"] || ENV['AWS_REGION'] || Aws.config[:region], + ) + else + Aws::S3::Client.new( + region: ENV["TORI_AWS_REGION"] || ENV['AWS_REGION'] || Aws.config[:region] + ) + end end def get_object(key:) client.get_object bucket: @bucket, key: key end @@ -96,11 +100,11 @@ def head_bucket client.head_bucket bucket: @bucket end - def put_object(key:, body:) - client.put_object bucket: @bucket, key: key, body: body + def put_object(opts = {}) + client.put_object({bucket: @bucket}.merge(opts)) end def delete_object(key:) client.delete_object bucket: @bucket, key: key end