Module: Studio::S3

Defined in:
lib/studio/s3.rb

Defined Under Namespace

Classes: Error, NotConfigured

Class Method Summary collapse

Class Method Details

.bucketObject

Raises:



44
45
46
47
48
# File 'lib/studio/s3.rb', line 44

def bucket
  prefix = Studio.s3_bucket_prefix
  raise NotConfigured, "Studio.s3_bucket_prefix not set in config/initializers/studio.rb" if prefix.nil? || prefix.empty?
  "#{prefix}-#{environment}"
end

.clientObject



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

def client
  @client ||= begin
    require "aws-sdk-s3"
    Aws::S3::Client.new(region: region)
  end
end

.delete(key:) ⇒ Object



35
36
37
# File 'lib/studio/s3.rb', line 35

def delete(key:)
  client.delete_object(bucket: bucket, key: key)
end

.download(key:) ⇒ Object



15
16
17
# File 'lib/studio/s3.rb', line 15

def download(key:)
  client.get_object(bucket: bucket, key: key).body.read
end

.exists?(key:) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
32
33
# File 'lib/studio/s3.rb', line 28

def exists?(key:)
  client.head_object(bucket: bucket, key: key)
  true
rescue Aws::S3::Errors::NotFound, Aws::S3::Errors::NoSuchKey
  false
end

.list(prefix: nil, max: 1000) ⇒ Object



39
40
41
42
# File 'lib/studio/s3.rb', line 39

def list(prefix: nil, max: 1000)
  resp = client.list_objects_v2(bucket: bucket, prefix: prefix, max_keys: max)
  resp.contents.map(&:key)
end

.regionObject



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

def region
  Studio.s3_region
end

.reset!Object



61
62
63
# File 'lib/studio/s3.rb', line 61

def reset!
  @client = nil
end

.signed_url(key:, expires_in: 3600) ⇒ Object



23
24
25
26
# File 'lib/studio/s3.rb', line 23

def signed_url(key:, expires_in: 3600)
  require "aws-sdk-s3"
  Aws::S3::Presigner.new(client: client).presigned_url(:get_object, bucket: bucket, key: key, expires_in: expires_in)
end

.upload(key:, body:, content_type: nil, cache_control: nil) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/studio/s3.rb', line 7

def upload(key:, body:, content_type: nil, cache_control: nil)
  opts = { bucket: bucket, key: key, body: body }
  opts[:content_type] = content_type if content_type
  opts[:cache_control] = cache_control if cache_control
  client.put_object(**opts)
  url(key: key)
end

.url(key:) ⇒ Object



19
20
21
# File 'lib/studio/s3.rb', line 19

def url(key:)
  "https://#{bucket}.s3.#{region}.amazonaws.com/#{key}"
end