Class: DataKeeper::S3Storage::Client

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

Constant Summary collapse

NoSuchKey =
Class.new(StandardError)

Instance Method Summary collapse

Constructor Details

#initialize(client_options:, bucket: nil) ⇒ Client

Returns a new instance of Client.



12
13
14
15
16
# File 'lib/data_keeper/s3_storage.rb', line 12

def initialize(client_options:, bucket: nil)
  @client_options = client_options
  @client = Aws::S3::Client.new(client_options)
  @bucket = bucket
end

Instance Method Details

#delete_files(file_paths) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/data_keeper/s3_storage.rb', line 18

def delete_files(file_paths)
  @client.delete_objects(
    bucket: @bucket,
    delete: {
      objects: file_paths.map { |key| { key: key } }
    }
  )
end

#list_contents(prefix = '') ⇒ Object



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

def list_contents(prefix = '')
  @client.list_objects(bucket: @bucket, prefix: prefix).contents
rescue Aws::S3::Errors::NoSuchKey
  raise NoSuchKey, prefix
end

#put_file(target_path, file, options = {}) ⇒ Object

Uploads the given file into the target_path in the s3 bucket. ‘file` must be a file stored locally. Can be either a raw string (path), or a File/Tempfile object (close is up to you).



47
48
49
50
51
52
53
# File 'lib/data_keeper/s3_storage.rb', line 47

def put_file(target_path, file, options = {})
  file.rewind if file.respond_to?(:rewind)

  s3 = Aws::S3::Resource.new(@client_options)
  obj = s3.bucket(@bucket).object(target_path)
  obj.upload_file(file, options)
end

#stream_to_io(path, io, opts = {}) ⇒ Object

Streams all contents from ‘path` into the provided io object, calling #write to it. io can be a File, or any other IO-like object.



35
36
37
38
39
40
41
42
# File 'lib/data_keeper/s3_storage.rb', line 35

def stream_to_io(path, io, opts = {})
  @client.get_object(opts.merge(
    bucket: @bucket,
    key: path
  ), target: io)
rescue Aws::S3::Errors::NoSuchKey
  raise NoSuchKey, path
end