-
-
Save ahoward/ba88487f9c9fb005cad2 to your computer and use it in GitHub Desktop.
working with buckets across regions is just silly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def s3_any_client(&block) | |
| client = Aws::S3::Client.new | |
| begin | |
| block.call(client) | |
| rescue Aws::S3::Errors::Http301Error | |
| client = Aws::S3::Client.new(:endpoint => 'https://s3.amazonaws.com') | |
| block.call(client) | |
| end | |
| end | |
| def s3_bucket_region(bucket = s3_bucket_name) | |
| s3_any_client do |client| | |
| region = client.get_bucket_location(:bucket => bucket).first.to_hash[:location_constraint] | |
| region.blank? ? "us-east-1" : region | |
| end | |
| end | |
| def s3_bucket_exists(name = s3_bucket_name) | |
| s3_any_client do |client| | |
| begin | |
| client.head_bucket(:bucket => name) | |
| true | |
| rescue Aws::S3::Errors::Forbidden | |
| true | |
| rescue Aws::S3::Errors::NotFound | |
| false | |
| end | |
| end | |
| end | |
| alias_method :s3_bucket_exists?, :s3_bucket_exists | |
| def s3_bucket_create!(name = s3_bucket_name) | |
| unless s3_bucket_exists?(name) | |
| client = Aws::S3::Client.new | |
| bucket = Aws::S3::Bucket.new(:name => name, :client => client) | |
| begin | |
| bucket.create | |
| rescue Aws::S3::Errors::BucketAlreadyOwnedByYou | |
| end | |
| bucket.exists? | |
| else | |
| bucket = Aws::S3::Bucket.new(:name => name, :client => client) | |
| bucket.exists? | |
| end | |
| end | |
| def s3_bucket(name = s3_bucket_name) | |
| @s3_bucket ||= ( | |
| s3_bucket_create!(name) unless s3_bucket_exists?(name) | |
| region = s3_bucket_region(name) | |
| bucket = Aws::S3::Bucket.new(:name => name, :region => region) | |
| bucket | |
| ) | |
| end | |
| alias_method :bucket, :s3_bucket | |
| def s3_bucket_name | |
| App.settings.get(:aws, :s3, :bucket) | |
| end | |
| alias_method :bucket_name, :s3_bucket_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment