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