lib/tori/backend/s3.rb in tori-0.1.0 vs lib/tori/backend/s3.rb in tori-0.2.0

- old
+ new

@@ -4,19 +4,38 @@ module Tori module Backend class S3 DEFAULT_CONTENT_TYPE = 'text/plain'.freeze attr_accessor :bucket + attr_reader :client + # Must be set bucket name. # And it use aws-sdk-core >= 2.0 - # ENV["TORI_ACCESS_KEY"] > aws-sdk credentials + # ENV takes precedence over credentials file and instance profile # # example: # Tori.config.backend = Tori::Backend::S3.new(bucket: 'tori_bucket') - def initialize(bucket:) + def initialize(bucket:, client: nil) @bucket = bucket - @client = nil + if client + unless client.kind_of?(Aws::S3::Client) + raise TypeError, "client should be instance of Aws::S3::Client or nil" + end + @client = client + else + region = ENV['TORI_AWS_REGION'] || ENV['AWS_REGION'] || Aws.config[:region] + @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: region, + ) + else + # Use instance profile or credentials file (~/.aws/credentials) + Aws::S3::Client.new(region: region) + end + end end def write(filename, resource, opts = nil) opts ||= {} case resource @@ -86,23 +105,9 @@ end def url_for(filename, method) signer = Aws::S3::Presigner.new(client: client) signer.presigned_url(method, bucket: @bucket, key: filename) - end - - 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 end def get_object(key:) client.get_object bucket: @bucket, key: key end