Skip to content
This repository has been archived by the owner on Jul 13, 2023. It is now read-only.

Commit

Permalink
Create a bucket if one doesn't exist.
Browse files Browse the repository at this point in the history
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
Jon Yurek committed Oct 1, 2010
1 parent 9e6afe4 commit 05498d2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/paperclip/storage/s3.rb
Expand Up @@ -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
Expand All @@ -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
Expand Down
15 changes: 15 additions & 0 deletions test/storage_test.rb
Expand Up @@ -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)
Expand Down

0 comments on commit 05498d2

Please sign in to comment.