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

Public Class Methods

create(name, options = {}) click to toggle source

Creates a bucket named name.

Bucket.create('jukebox')

Your bucket name must be unique across all of S3. If the name you request has already been taken, you will get a 409 Conflict response, and a BucketAlreadyExists exception will be raised.

By default new buckets have their access level set to private. You can override this using the :access option.

Bucket.create('internet_drop_box', :access => :public_read_write)

The full list of access levels that you can set on Bucket and S3Object creation are listed in the README in the section called 'Setting access levels'.

   # File lib/aws/s3/bucket.rb
77 def create(name, options = {})
78   validate_name!(name)
79   put("/#{name}", options).success?
80 end
delete(name = nil, options = {}) click to toggle source

Deletes the bucket named name.

All objects in the bucket must be deleted before the bucket can be deleted. If the bucket is not empty, BucketNotEmpty will be raised.

You can side step this issue by passing the :force => true option to delete which will take care of emptying the bucket before deleting it.

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

Only the owner of a bucket can delete a bucket, regardless of the bucket's access control policy.

    # File lib/aws/s3/bucket.rb
159 def delete(name = nil, options = {})
160   find(name).delete_all if options[:force]
161   
162   name = path(name)
163   Base.delete(name).success?
164 end
find(name = nil, options = {}) click to toggle source

Fetches the bucket named name.

Bucket.find('jukebox')

If a default bucket is inferable from the current connection's subdomain, or if set explicitly with Base.set_current_bucket, it will be used if no bucket is specified.

MusicBucket.current_bucket
=> 'jukebox'
MusicBucket.find.name
=> 'jukebox'

By default all objects contained in the bucket will be returned (sans their data) along with the bucket. You can access your objects using the Bucket#objects method.

Bucket.find('jukebox').objects

There are several options which allow you to limit which objects are retrieved. The list of object filtering options are listed in the documentation for Bucket.objects.

    # File lib/aws/s3/bucket.rb
101 def find(name = nil, options = {})
102   new(get(path(name, options)).bucket)
103 end
list(reload = false) click to toggle source

List all your buckets. This is a convenient wrapper around AWS::S3::Service.buckets.

    # File lib/aws/s3/bucket.rb
167 def list(reload = false)
168   Service.buckets(reload)
169 end
objects(name = nil, options = {}) click to toggle source

Return just the objects in the bucket named name.

By default all objects of the named bucket will be returned. There are options, though, for filtering which objects are returned.

Object filtering options

  • :max_keys - The maximum number of keys you'd like to see in the response body. The server may return fewer than this many keys, but will not return more.

    Bucket.objects('jukebox').size
    # => 3
    Bucket.objects('jukebox', :max_keys => 1).size
    # => 1
    
  • :prefix - Restricts the response to only contain results that begin with the specified prefix.

    Bucket.objects('jukebox')
    # => [<AWS::S3::S3Object '/jazz/miles.mp3'>, <AWS::S3::S3Object '/jazz/dolphy.mp3'>, <AWS::S3::S3Object '/classical/malher.mp3'>]
    Bucket.objects('jukebox', :prefix => 'classical')
    # => [<AWS::S3::S3Object '/classical/malher.mp3'>]
    
  • :marker - Marker specifies where in the result set to resume listing. It restricts the response to only contain results that occur alphabetically after the value of marker. To retrieve the next set of results, use the last key from the current page of results as the marker in your next request.

    # Skip 'mahler'
    Bucket.objects('jukebox', :marker => 'mb')
    # => [<AWS::S3::S3Object '/jazz/miles.mp3'>]
    

Examples

# Return no more than 2 objects whose key's are listed alphabetically after the letter 'm'.
Bucket.objects('jukebox', :marker => 'm', :max_keys => 2)
# => [<AWS::S3::S3Object '/jazz/miles.mp3'>, <AWS::S3::S3Object '/classical/malher.mp3'>]

# Return no more than 2 objects whose key's are listed alphabetically after the letter 'm' and have the 'jazz' prefix.
Bucket.objects('jukebox', :marker => 'm', :max_keys => 2, :prefix => 'jazz')
# => [<AWS::S3::S3Object '/jazz/miles.mp3'>]
    # File lib/aws/s3/bucket.rb
144 def objects(name = nil, options = {})
145   find(name, options).object_cache
146 end

Private Class Methods

path(name, options = {}) click to toggle source
    # File lib/aws/s3/bucket.rb
176 def path(name, options = {})
177   if name.is_a?(Hash)
178     options = name
179     name    = nil
180   end
181   "/#{bucket_name(name)}#{RequestOptions.process(options).to_query_string}"
182 end
validate_name!(name) click to toggle source
    # File lib/aws/s3/bucket.rb
172 def validate_name!(name)
173   raise InvalidBucketName.new(name) unless name =~ /^[-\w.]{3,255}$/
174 end

Public Instance Methods

[](object_key) click to toggle source

Fetches the object named object_key, or nil if the bucket does not contain an object with the specified key.

bucket.objects
=> [#<AWS::S3::S3Object '/marcel_molina/beluga_baby.jpg'>,
    #<AWS::S3::S3Object '/marcel_molina/tongue_overload.jpg'>]
bucket['beluga_baby.jpg']
=> #<AWS::S3::S3Object '/marcel_molina/beluga_baby.jpg'>
    # File lib/aws/s3/bucket.rb
203 def [](object_key)
204   detect {|file| file.key == object_key.to_s}
205 end
clear()
Alias for: delete_all
delete(options = {}) click to toggle source

Deletes the bucket. See its class method counter part Bucket.delete for caveats about bucket deletion and how to ensure a bucket is deleted no matter what.

    # File lib/aws/s3/bucket.rb
268 def delete(options = {})
269   self.class.delete(name, options)
270 end
delete_all() click to toggle source

Delete all files in the bucket. Use with caution. Can not be undone.

    # File lib/aws/s3/bucket.rb
273 def delete_all
274   each do |object|
275     object.delete
276   end
277   self
278 end
Also aliased as: clear
each(&block) click to toggle source

Iterates over the objects in the bucket.

bucket.each do |object|
  # Do something with the object ...
end
    # File lib/aws/s3/bucket.rb
251 def each(&block)
252   # Dup the collection since we might be destructively modifying the object_cache during the iteration.
253   objects.dup.each(&block)
254 end
empty?() click to toggle source

Returns true if there are no objects in the bucket.

    # File lib/aws/s3/bucket.rb
257 def empty?
258   objects.empty?
259 end
new_object(attributes = {}) click to toggle source

Initializes a new S3Object belonging to the current bucket.

object = bucket.new_object
object.value = data
object.key   = 'classical/mahler.mp3'
object.store
bucket.objects.include?(object)
=> true
    # File lib/aws/s3/bucket.rb
215 def new_object(attributes = {})
216   object = S3Object.new(attributes)
217   register(object)
218   object
219 end
objects(options = {}) click to toggle source

List S3Object's of the bucket.

Once fetched the objects will be cached. You can reload the objects by passing :reload.

bucket.objects(:reload)

You can also filter the objects using the same options listed in Bucket.objects.

bucket.objects(:prefix => 'jazz')

Using these filtering options will implictly reload the objects.

To reclaim all the objects for the bucket you can pass in :reload again.

    # File lib/aws/s3/bucket.rb
234 def objects(options = {})
235   if options.is_a?(Hash)
236     reload = !options.empty?
237   else
238     reload  = options
239     options = {}
240   end
241   
242   reload!(options) if reload || object_cache.empty?
243   object_cache
244 end
size() click to toggle source

Returns the number of objects in the bucket.

    # File lib/aws/s3/bucket.rb
262 def size
263   objects.size
264 end

Private Instance Methods

add(object) click to toggle source
    # File lib/aws/s3/bucket.rb
302 def add(object)
303   register(object)
304   object_cache << object
305 end
build_contents!() click to toggle source
    # File lib/aws/s3/bucket.rb
291 def build_contents!
292   return unless has_contents?
293   attributes.delete('contents').each do |content|
294     add new_object(content)
295   end
296 end
has_contents?() click to toggle source
    # File lib/aws/s3/bucket.rb
298 def has_contents?
299   attributes.has_key?('contents')
300 end
register(object) click to toggle source
    # File lib/aws/s3/bucket.rb
307 def register(object)
308   object.bucket = self
309 end
reload!(options = {}) click to toggle source
    # File lib/aws/s3/bucket.rb
311 def reload!(options = {})
312   object_cache.clear
313   self.class.objects(name, options).each do |object| 
314     add object
315   end
316 end