Class: BulkProcessor::S3File

Inherits:
Object
  • Object
show all
Defined in:
lib/bulk_processor/s3_file.rb

Overview

Read and write files in a pre-configured S3 bucket.

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ S3File

Returns a new instance of S3File.

Parameters:

  • key (String)

    the unique identifier (within the bucket) used to access the file



11
12
13
# File 'lib/bulk_processor/s3_file.rb', line 11

def initialize(key)
  @key = "#{NAMESPACE}/#{key}"
end

Instance Method Details

#deleteObject



46
47
48
# File 'lib/bulk_processor/s3_file.rb', line 46

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

#exists?Boolean

Returns:

  • (Boolean)


15
16
17
18
19
20
# File 'lib/bulk_processor/s3_file.rb', line 15

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

#openObject

Yield the file stored in the bucket identified by the key. The file is only guaranteed to exist locally within the block, any attempts to access the file outside of the block will fail.



27
28
29
30
31
32
33
34
# File 'lib/bulk_processor/s3_file.rb', line 27

def open
  with_temp_file do |local_file|
    object = client.get_object(bucket: bucket, key: key)
    local_file.write(object.body.read)
    local_file.rewind
    yield local_file
  end
end

#write(contents) ⇒ String

Write a new file to the bucket on S3

Parameters:

  • contents (String)

    the contents of the file to create

Returns:

  • (String)

    the URL of the new file



40
41
42
43
44
# File 'lib/bulk_processor/s3_file.rb', line 40

def write(contents)
  remote_file = resource.bucket(bucket).object(key)
  remote_file.put(body: contents)
  remote_file.public_url
end