class AWS::S3::Bucket

Buckets are containers for objects (the files you store on S3). To create a new bucket you just specify its name.

# Pick a unique name, or else you'll get an error
# if the name is already taken.
Bucket.create('jukebox')

Bucket names must be unique across the entire S3 system, sort of like domain names across the internet. If you try to create a bucket with a name that is already taken, you will get an error.

Assuming the name you chose isn’t already taken, your new bucket will now appear in the bucket list:

Service.buckets
# => [#<AWS::S3::Bucket @attributes={"name"=>"jukebox"}>]

Once you have succesfully created a bucket you can you can fetch it by name using Bucket.find.

music_bucket = Bucket.find('jukebox')

The bucket that is returned will contain a listing of all the objects in the bucket.

music_bucket.objects.size
# => 0

If all you are interested in is the objects of the bucket, you can get to them directly using Bucket.objects.

Bucket.objects('jukebox').size
# => 0

By default all objects will be returned, though there are several options you can use to limit what is returned, such as specifying that only objects whose name is after a certain place in the alphabet be returned, and etc. Details about these options can be found in the documentation for Bucket.find.

To add an object to a bucket you specify the name of the object, its value, and the bucket to put it in.

file = 'black-flowers.mp3'
S3Object.store(file, open(file), 'jukebox')

You’ll see your file has been added to it:

music_bucket.objects
# => [#<AWS::S3::S3Object '/jukebox/black-flowers.mp3'>]

You can treat your bucket like a hash and access objects by name:

jukebox['black-flowers.mp3']
# => #<AWS::S3::S3Object '/jukebox/black-flowers.mp3'>

In the event that you want to delete a bucket, you can use Bucket.delete.

Bucket.delete('jukebox')

Keep in mind, like unix directories, you can not delete a bucket unless it is empty. Trying to delete a bucket that contains objects will raise a BucketNotEmpty exception.

Passing the :force => true option to delete will take care of deleting all the bucket’s objects for you.

Bucket.delete('photos', :force => true)
# => true