Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Create a bucket if one doesn't exist.

This method prevents excessive calls to the S3 API, creating a bucket
only if the store method fails with a NoSuchBucket error instead of
asking for the bucket before each request.
  • Loading branch information...
commit 05498d27d75a52d9298f0982e675b9240ca6d01e 1 parent 9e6afe4
@jyurek jyurek authored
Showing with 22 additions and 0 deletions.
  1. +7 −0 lib/paperclip/storage/s3.rb
  2. +15 −0 test/storage_test.rb
View
7 lib/paperclip/storage/s3.rb
@@ -133,6 +133,10 @@ def to_file style = default_style
return file
end
+ def create_bucket
+ AWS::S3::Bucket.create(bucket_name)
+ end
+
def flush_writes #:nodoc:
@queued_for_write.each do |style, file|
begin
@@ -143,6 +147,9 @@ def flush_writes #:nodoc:
{:content_type => instance_read(:content_type),
:access => @s3_permissions,
}.merge(@s3_headers))
+ rescue AWS::S3::NoSuchBucket => e
+ create_bucket
+ retry
rescue AWS::S3::ResponseError => e
raise
end
View
15 test/storage_test.rb
@@ -185,6 +185,21 @@ def rails_env(env)
end
end
+ context "and saved without a bucket" do
+ setup do
+ class AWS::S3::NoSuchBucket < AWS::S3::ResponseError
+ # Force the class to be created as a proper subclass of ResponseError thanks to AWS::S3's autocreation of exceptions
+ end
+ AWS::S3::Bucket.expects(:create).with("testing")
+ AWS::S3::S3Object.stubs(:store).raises(AWS::S3::NoSuchBucket.new(:message, :response)).then.returns(true)
+ @dummy.save
+ end
+
+ should "succeed" do
+ assert true
+ end
+ end
+
context "and remove" do
setup do
AWS::S3::S3Object.stubs(:exists?).returns(true)
Please sign in to comment.
Something went wrong with that request. Please try again.