Class: Saviour::S3Storage

Inherits:
Object
  • Object
show all
Defined in:
lib/saviour/s3_storage.rb

Instance Method Summary collapse

Constructor Details

#initialize(conf = {}) ⇒ S3Storage

Returns a new instance of S3Storage.



5
6
7
8
9
10
11
12
13
# File 'lib/saviour/s3_storage.rb', line 5

def initialize(conf = {})
  @bucket = conf.delete(:bucket)
  @public_url_prefix = conf.delete(:public_url_prefix)
  @conf = conf
  @overwrite_protection = conf.delete(:overwrite_protection) { true }
  @create_options = conf.delete(:create_options) { {} }
  conf.fetch(:aws_access_key_id) { raise ArgumentError.new("aws_access_key_id is required") }
  conf.fetch(:aws_secret_access_key) { raise ArgumentError.new("aws_secret_access_key is required") }
end

Instance Method Details

#delete(path) ⇒ Object



33
34
35
36
37
# File 'lib/saviour/s3_storage.rb', line 33

def delete(path)
  path = sanitize_leading_slash(path)
  assert_exists(path)
  directory.files.get(path).destroy
end

#exists?(path) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
# File 'lib/saviour/s3_storage.rb', line 39

def exists?(path)
  path = sanitize_leading_slash(path)
  !!directory.files.head(path)
end

#public_url(path) ⇒ Object

Raises:

  • (RuntimeError)


44
45
46
47
48
49
# File 'lib/saviour/s3_storage.rb', line 44

def public_url(path)
  raise(RuntimeError, "You must provide a `public_url_prefix`") unless public_url_prefix

  path = sanitize_leading_slash(path)
  ::File.join(public_url_prefix, path)
end

#read(path) ⇒ Object



27
28
29
30
31
# File 'lib/saviour/s3_storage.rb', line 27

def read(path)
  path = sanitize_leading_slash(path)
  assert_exists(path)
  directory.files.get(path).body
end

#write(contents, path) ⇒ Object

Raises:

  • (RuntimeError)


15
16
17
18
19
20
21
22
23
24
25
# File 'lib/saviour/s3_storage.rb', line 15

def write(contents, path)
  raise(RuntimeError, "The path you're trying to write already exists!") if @overwrite_protection && exists?(path)

  path = sanitize_leading_slash(path)
  directory.files.create({
                             key: path,
                             body: contents,
                             public: true
                         }.merge(@create_options)
  )
end