class Selectel::S3::Uploader

Attributes

container_name[R]
s3_resource[R]

Public Class Methods

new(container_name) click to toggle source
# File lib/selectel/s3/uploader.rb, line 7
def initialize(container_name)
  @s3_resource = Aws::S3::Resource.new(
    region: config.region, access_key_id: config.access_key_id,
    secret_access_key: config.secret_access_key, endpoint: config.endpoint
  )
  @container_name = container_name
end

Public Instance Methods

upload_file(file_path, remote_path = file_path) click to toggle source
# File lib/selectel/s3/uploader.rb, line 25
def upload_file(file_path, remote_path = file_path)
  object = s3_resource.bucket(container_name).object(remote_path)

  object.upload_file(file_path)
end
upload_folder(folder_path, remote_path) click to toggle source
# File lib/selectel/s3/uploader.rb, line 31
def upload_folder(folder_path, remote_path)
  started_at = Time.now
  absolute_folder_path = File.expand_path(folder_path)
  files = fetch_all_files(absolute_folder_path)

  files.each do |file_path|
    remote_file_path = file_path.sub(absolute_folder_path, remote_path)

    upload_file(file_path, remote_file_path)
  end

  puts "Uploaded #{ files.size } files for #{ Time.now - started_at } seconds"
end
upload_remote_file(file_url, remote_path) click to toggle source
# File lib/selectel/s3/uploader.rb, line 15
def upload_remote_file(file_url, remote_path)
  object = s3_resource.bucket(container_name).object(remote_path)

  file = fetch_file(file_url)

  object.upload_file(file)

  file.delete
end

Private Instance Methods

config() click to toggle source
# File lib/selectel/s3/uploader.rb, line 49
def config
  @config ||= S3.configuration
end
fetch_all_files(folder_path) click to toggle source
# File lib/selectel/s3/uploader.rb, line 53
def fetch_all_files(folder_path)
  Dir["#{ folder_path }/**/*"].select { |path| File.file?(path) }
end
fetch_file(file_url) click to toggle source
# File lib/selectel/s3/uploader.rb, line 57
def fetch_file(file_url)
  file = open(file_url)

  return file unless file.is_a?(StringIO)

  result = Tempfile.new

  File.write(result.path, file.string.force_encoding('UTF-8'))

  result
end