Sha256: 3db09c71fdcb9e47b5eededc9863cb5faae3d50fed1a277656705b6f0d8714d3

Contents?: true

Size: 1.86 KB

Versions: 5

Compression:

Stored size: 1.86 KB

Contents

module AwsClient
  class S3Wrapper < AwsClient::Wrapper

    BUCKET_DEFINITION_FILE = ".aws_buckets"
    PATH_TO_BUCKETS_DEFINITION = File.join(Dir.home, BUCKET_DEFINITION_FILE)

    def initialize(*params)
      super
      @credentials_key = params[0][:credentials_key]
      @aws_region = params[0][:region]
    end
 
    def resource
      @resource ||= Aws::S3::Resource.new(client: client)
    end

    def bucket_object_for_bucket_prefix(bucket_prefix_code)
      bucket = find_or_create_bucket_for(bucket_prefix_code)
      return bucket.objects.collect{|object| object.object } # 'object.object' The S3 object belonging to the S3 resource    
    end

    def find_bucket_by(bucket_name)
      buckets.select{|bucket| bucket.name == bucket_name }.first
    end

    def write_file_to_bucket(bucket_prefix_code, file_path)
      bucket = find_or_create_bucket_for(bucket_prefix_code)
      s3_object = bucket.put_object(
        :key => File.basename(file_path),
        :body => IO.read(file_path)
      )
      puts "\nRemote file"
      puts "#{s3_object.public_url}"
      return s3_object
    end

    def buckets
      return resource.buckets
    end

    def find_or_create_bucket_for(bucket_prefix_code)
      bucket_prefix = bucket_prefixes[bucket_prefix_code]
      full_bucket_name = bucket_name_for_function(bucket_prefix) 
      return find_or_create_bucket(full_bucket_name)
    end
  
    def bucket_name_for_function(bucket_function)
      return "#{bucket_function}.#{@credentials_key}.#{@aws_region}"  
    end

    def bucket_prefixes
      YAML.load_file(PATH_TO_BUCKETS_DEFINITION)
    end

    private

    def find_or_create_bucket(bucket_name)
      begin 
        bucket = resource.create_bucket(:bucket => bucket_name)
      rescue Aws::S3::Errors::BucketAlreadyOwnedByYou
        bucket = find_bucket_by(bucket_name)
      end

      return bucket
    end

  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
aws_client-0.0.5 lib/s3_wrapper.rb
aws_client-0.0.4 lib/s3_wrapper.rb
aws_client-0.0.3 lib/s3_wrapper.rb
aws_client-0.0.2 lib/s3_wrapper.rb
aws_client-0.0.1 lib/s3_wrapper.rb