Module: Storage::Strategies::S3

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

Constant Summary collapse

MissingBucket =
Class.new(StandardError)

Instance Method Summary collapse

Instance Method Details

#connect!Object



21
22
# File 'lib/storage/strategies/s3.rb', line 21

def connect!
end

#connectionObject



8
9
10
11
12
13
14
15
# File 'lib/storage/strategies/s3.rb', line 8

def connection
  @connection ||= Fog::Storage.new(
    provider: "AWS",
    aws_access_key_id: Storage::Config.access_key,
    aws_secret_access_key: Storage::Config.secret_key,
    region: Storage::Config.region
  )
end

#create_bucket(name) ⇒ Object



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

def create_bucket(name)
  connection.directories.create(
    key: name,
    public: false
  )
end

#create_object(bucket, file, options) ⇒ Object



61
62
63
64
65
66
67
# File 'lib/storage/strategies/s3.rb', line 61

def create_object(bucket, file, options)
  bucket.files.create(
    key: options.fetch(:name),
    body: file,
    public: (options[:public] || options[:access] == :public_read)
  )
end

#disconnect!Object



24
25
26
# File 'lib/storage/strategies/s3.rb', line 24

def disconnect!
  @connection = nil
end

#find_bucket(name) ⇒ Object



46
47
48
# File 'lib/storage/strategies/s3.rb', line 46

def find_bucket(name)
  connection.directories.get(name)
end

#find_bucket!(name) ⇒ Object



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

def find_bucket!(name)
  find_bucket(name) || fail(MissingBucket)
end

#find_bucket_or_create(name) ⇒ Object



77
78
79
# File 'lib/storage/strategies/s3.rb', line 77

def find_bucket_or_create(name)
  find_bucket(name) || create_bucket(name)
end

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



69
70
71
72
73
74
75
# File 'lib/storage/strategies/s3.rb', line 69

def find_object(file, options = {})
  path = options.fetch(:name, file)
  bucket = find_bucket!(options.fetch(:bucket))
  bucket.files.get(path) || fail(MissingFileError)
rescue MissingBucket
  raise MissingFileError
end

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



28
29
30
31
32
# File 'lib/storage/strategies/s3.rb', line 28

def get(file, options = {})
  expires = options.fetch(:expires, Time.now.to_i + 3600)
  object = find_object(file, options)
  object.public_url || object.url(expires)
end

#prepare!Object



17
18
19
# File 'lib/storage/strategies/s3.rb', line 17

def prepare!
  disconnect!
end

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



41
42
43
44
# File 'lib/storage/strategies/s3.rb', line 41

def remove(file, options = {})
  object = find_object(file, options)
  object.destroy
end

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



34
35
36
37
38
39
# File 'lib/storage/strategies/s3.rb', line 34

def store(file, options = {})
  bucket = find_bucket_or_create(options.fetch(:bucket))
  file = File.open(file, "rb") unless file.respond_to?(:read) && !file.kind_of?(Pathname)

  create_object(bucket, file, options)
end