lib/storage/strategies/s3.rb in storage-0.1.5 vs lib/storage/strategies/s3.rb in storage-0.2.0

- old
+ new

@@ -1,60 +1,84 @@ module Storage module Strategies module S3 extend self + MissingBucket = Class.new(StandardError) + + def connection + @connection ||= Fog::Storage.new({ + :provider => 'AWS', + :aws_access_key_id => Storage::Config.access_key, + :aws_secret_access_key => Storage::Config.secret_key + }) + end + + def prepare! + disconnect! + end + def connect! - AWS::S3::Base.establish_connection!({ - :access_key_id => Storage::Config.access_key, - :secret_access_key => Storage::Config.secret_key - }) unless AWS::S3::Base.connected? end def disconnect! - AWS::S3::Base.disconnect! if AWS::S3::Base.connected? + @connection = nil end def get(file, options = {}) - connect! + expires = options.fetch(:expires, Time.now.to_i + 3600) object = find_object(file, options) - AWS::S3::S3Object.url_for(file, options[:bucket], :authenticated => false) - rescue AWS::S3::NoSuchKey, AWS::S3::NoSuchBucket - raise Storage::MissingFileError + object.public_url || object.url(expires) end def store(file, options = {}) - connect! object = find_object(file, options) rescue nil + raise FileAlreadyExistsError if object - raise Storage::FileAlreadyExistsError if object - - bucket = find_bucket_or_create(options[:bucket]) + bucket = find_bucket_or_create(options.fetch(:bucket)) file = File.open(file, "rb") unless file.respond_to?(:read) && !file.kind_of?(Pathname) - AWS::S3::S3Object.store(options[:name], file, bucket.name, :access => options.fetch(:access, :public_read)) + + create_object(bucket, file, options) end def remove(file, options = {}) - connect! object = find_object(file, options) - object.delete - rescue AWS::S3::NoSuchKey, AWS::S3::NoSuchBucket - raise Storage::MissingFileError + object.destroy end def find_bucket(name) - AWS::S3::Bucket.find(name) + connection.directories.get(name) end + def find_bucket!(name) + find_bucket(name) || raise(MissingBucket) + end + + def create_bucket(name) + connection.directories.create( + :key => name, + :public => false + ) + end + + def create_object(bucket, file, options) + bucket.files.create({ + :key => options.fetch(:name), + :body => file, + :public => (options[:public] || options[:access] != :public_read) + }) + end + def find_object(file, options = {}) path = options.fetch(:name, file) - AWS::S3::S3Object.find(path, options[:bucket]) + bucket = find_bucket!(options.fetch(:bucket)) + bucket.files.get(path) || raise(MissingFileError) + rescue MissingBucket + raise MissingFileError end def find_bucket_or_create(name) - bucket = find_bucket(name) - bucket ||= AWS::S3::Bucket.create(name) - bucket + find_bucket(name) || create_bucket(name) end end end end