Class: TeakUtil::Storage::S3

Inherits:
Object
  • Object
show all
Defined in:
lib/teak_util/storage/s3.rb

Overview

Wraps access to S3 in a simpler key/value API.

Instance Method Summary collapse

Constructor Details

#initialize(bucket, client: nil, prefix: '', server_side_encryption: 'aws:kms', kms_key_id: nil, acl: 'private') ⇒ S3



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/teak_util/storage/s3.rb', line 18

def initialize(bucket, client: nil, prefix: '', server_side_encryption: 'aws:kms',
               kms_key_id: nil, acl: 'private')

  client ||= Aws::S3::Client.new
  @bucket = Aws::S3::Resource.new(client: client).bucket(bucket)
  @prefix = prefix

  @put_opts = {
    acl: acl,
    server_side_encryption: server_side_encryption
  }

  @put_opts[:ssekms_key_id] = kms_key_id if kms_key_id
end

Instance Method Details

#bucket_nameObject

Returns the name of the bucket.



73
74
75
# File 'lib/teak_util/storage/s3.rb', line 73

def bucket_name
  @bucket.name
end

#del(key) ⇒ Object

Deletes the value stored at key



60
61
62
# File 'lib/teak_util/storage/s3.rb', line 60

def del(key)
  @bucket.object(prefixed_path(key)).delete
end

#get(key) ⇒ Object

Retrieves the value stored at key



50
51
52
53
54
55
56
# File 'lib/teak_util/storage/s3.rb', line 50

def get(key)
  begin
    @bucket.object(prefixed_path(key)).get.body.read
  rescue Aws::S3::Errors::NoSuchKey
    return nil
  end
end

#public_url(key, expires_in: 1.week) ⇒ Object

Returns a URL which allows public access to the data stored at key



67
68
69
70
# File 'lib/teak_util/storage/s3.rb', line 67

def public_url(key, expires_in: 1.week)
  path = "#{@prefix}#{key}"
  @bucket.object(path).presigned_url(:get, expires_in: expires_in.to_i)
end

#put(key, value, opts = {}) ⇒ Object

Set key to hold the string value. If a key already holds a value it is overwritten.

Options Hash (opts):

  • :content_type (String)

    A standard MIME type describing the format of the contents.

  • :content_disposition (String)

    Specifies presentational information for the object.



40
41
42
43
44
45
46
# File 'lib/teak_util/storage/s3.rb', line 40

def put(key, value, opts = {})
  path = prefixed_path(key)
  @bucket.object(path).put(
    opts.merge(@put_opts.merge(body: value))
  )
  path
end