Module: Storage::Strategies::S3

Extended by:
S3
Included in:
S3
Defined in:
lib/storage/strategies/s3.rb

Instance Method Summary collapse

Instance Method Details

#connect!Object



6
7
8
9
10
11
# File 'lib/storage/strategies/s3.rb', line 6

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

#disconnect!Object



13
14
15
# File 'lib/storage/strategies/s3.rb', line 13

def disconnect!
  AWS::S3::Base.disconnect! if AWS::S3::Base.connected?
end

#find_bucket(name) ⇒ Object



44
45
46
# File 'lib/storage/strategies/s3.rb', line 44

def find_bucket(name)
  AWS::S3::Bucket.find(name)
end

#find_bucket_or_create(name) ⇒ Object



53
54
55
56
57
# File 'lib/storage/strategies/s3.rb', line 53

def find_bucket_or_create(name)
  bucket = find_bucket(name)
  bucket ||= AWS::S3::Bucket.create(name)
  bucket
end

#find_object(file, options = {}) ⇒ Object



48
49
50
51
# File 'lib/storage/strategies/s3.rb', line 48

def find_object(file, options = {})
  path = options.fetch(:name, file)
  AWS::S3::S3Object.find(path, options[:bucket])
end

#get(file, options = {}) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/storage/strategies/s3.rb', line 17

def get(file, options = {})
  connect!
  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
end

#remove(file, options = {}) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/storage/strategies/s3.rb', line 36

def remove(file, options = {})
  connect!
  object = find_object(file, options)
  object.delete
rescue AWS::S3::NoSuchKey, AWS::S3::NoSuchBucket
  raise Storage::MissingFileError
end

#store(file, options = {}) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/storage/strategies/s3.rb', line 25

def store(file, options = {})
  connect!
  object = find_object(file, options) rescue nil

  raise Storage::FileAlreadyExistsError if object

  bucket = find_bucket_or_create(options[: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))
end