Class: MinimalPipeline::S3

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

Overview

Here is an example of how to use this class to interact with S3.

“` s3 = MinimalPipeline::S3.new

# Upload file s3.upload('bucket_name', 'foo.txt')

# Download file s3.download('bucket_name', 'foo.txt') “`

You will need the following environment variables to be present:

  • `AWS_REGION` or `region`

Instance Method Summary collapse

Constructor Details

#initializeS3

Initializes a `S3` client Requires environment variables `AWS_REGION` or `region` to be set.


23
24
25
26
27
28
29
# File 'lib/minimal_pipeline/s3.rb', line 23

def initialize
  raise 'You must set env variable AWS_REGION or region.' \
    if ENV['AWS_REGION'].nil? && ENV['region'].nil?

  region = ENV['AWS_REGION'] || ENV['region']
  @s3 = Aws::S3::Resource.new(region: region)
end

Instance Method Details

#download(bucket_name, file, key = nil) ⇒ Object

Downloads a file from S3 to local disk

This defaults to the file param

Parameters:

  • bucket_name (String)

    The name of S3 bucket to download from

  • file (String)

    The path to the file on disk to download to

  • key (String) (defaults to: nil)

    The name of the key of the object in S3


37
38
39
40
41
# File 'lib/minimal_pipeline/s3.rb', line 37

def download(bucket_name, file, key = nil)
  key ||= File.basename(file)
  object = @s3.bucket(bucket_name).object(key)
  object.download_file(file)
end

#upload(bucket_name, file, key = nil) ⇒ String

Uploads a file from local disk to S3

This defaults to the file param

Parameters:

  • bucket_name (String)

    The name of S3 bucket to upload to

  • file (String)

    The path to the file on disk to be uploaded

  • key (String) (defaults to: nil)

    The name of the key to store the file as in the bucket

Returns:

  • (String)

    The Version ID of the latest object


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

def upload(bucket_name, file, key = nil)
  key ||= File.basename(file)
  object = @s3.bucket(bucket_name).object(key)
  object.upload_file(file)
  object.load
  object.version_id
end