class S3Dir::Uploader

Attributes

bucket[R]
files_path[R]
is_public[R]
key[R]
storage[R]

Public Class Methods

new(dir, key, options) click to toggle source
# File lib/s3_dir.rb, line 44
def initialize dir, key, options
  @files_path = File.expand_path(dir)

  # Merge defaults with passed-in options
  settings = {credential: ENV['FOG_CREDENTIAL'],
              private: false}.merge(options)

  # Configure Fog
  Fog.credential = settings[:credential]

  # Get a region
  region = Fog.credentials[:region] || 'us-west-2'

  # If we don't specify this endpoint, Fog will complain about
  # not using the correct endpoint if the bucket has dots in
  # the name (i.e. website bucket)
  endpoint = 'http://s3.amazonaws.com'

  # This may be a public bucket
  @is_public = !settings[:private]

  # Set up our storage object
  # We have to specify path_style here because Fog will complain about
  # our website bucket (if we're using a bucket with dots in the name)
  # not being covered by the SSL certificate.
  fog_options = Fog.credentials.merge({provider: 'aws', path_style: true,
                                       region: region, endpoint: endpoint})
  fog_options.delete(:key_name)
  @storage = Fog::Storage.new(fog_options)
  @bucket = storage.directories.get(key)
  @bucket ||= storage.directories.create(key: key, public: is_public)
  @key = key
end

Public Instance Methods

upload() click to toggle source
# File lib/s3_dir.rb, line 78
def upload
  Dir.chdir(files_path) do
    Dir['**/*'].each do |entry|
      File.directory?(entry) ? create_directory(entry) : create_file(entry)
    end
  end
end

Private Instance Methods

create_directory(entry) click to toggle source
# File lib/s3_dir.rb, line 88
def create_directory entry
  storage.head_object(key, entry)
rescue Excon::Errors::NotFound
  bucket.files.create(key: entry, public: is_public)
end
create_file(entry) click to toggle source
# File lib/s3_dir.rb, line 94
def create_file entry
  storage.head_object(key, entry, {'If-Match' => md5(entry)})
rescue Excon::Errors::PreconditionFailed, Excon::Errors::NotFound
  bucket.files.create(key: entry, public: is_public, body: File.open(entry))
end
md5(entry) click to toggle source
# File lib/s3_dir.rb, line 100
def md5 entry
  Digest::MD5.hexdigest(File.read(entry))
end