# These methods are added to any Client with a bucket
# binding set.
module S33r
class Bucket < Client
attr_accessor :name
# +options+:
# * :check => true: if setting a :bucket option, the default behaviour is not to check
# whether the bucket actually exists on S3. If you pass this option,
# S33r will only set the bucket if it is on S3 and accessible;
# if it isn't, an error is raised (NoSuchBucket).
# * :create => true: if the bucket doesn't exist, try to create it.
# S33r will check before trying to create the bucket and will just return the
# bucket if it does.
def initialize(bucket_name, options={})
bucket_name_valid?(bucket_name)
super(options)
if options[:create]
options[:bucket] = bucket_name
raise last_response.s3_error unless do_put(nil, options).ok?
end
if options[:check]
raise InvalidBucket, "Bucket #{name} does not exist" unless bucket_exists?(bucket_name)
end
@name = bucket_name
yield self if block_given?
end
# Defaults for every request.
def request_defaults
super.merge(:bucket => name)
end
def exists?
bucket_exists?(name)
end
# Destroy this bucket.
#
# Pass :force => true to delete the content of
# the bucket if it exists.
def destroy(options={})
delete_bucket(name, options)
end
# Delete a key from inside the bucket.
def delete(key, options={})
options[:key] = key
do_delete(options).ok?
end
# List of keys in the bucket.
#
# +options+ are passed through to Client.listing.
#-- TODO: tests
def keys(options={})
listing(options).keys.sort
end
# Get an object from S3.
#
# By default, this will load the content of the object.
# If you don't want this, pass a :lazy option:
#
# bucket['key', :lazy]
def [](key, load_object=true)
options = {}
options[:lazy] = true if :lazy == load_object
object(key, options)
end
# +options+ are passed to bucket.get; in addition, you can use:
# * :lazy => true: this will prevent S33r from loading the
# content of the object from S3, instead just getting the object's
# metadata from the bucket listing.
def object(key, options={})
obj = listing[key]
if obj
obj.bucket = self
obj.fetch unless options[:lazy]
end
obj
end
# Can the bucket be used as a log target?
def log_receiver?
acl.log_targetable?
end
# Change whether the bucket can be used to receive logs.
#
# :on to make it a capable of receiving logs,
# :off to disable it as a log target.
def log_receiver(state=:on)
change_log_target_status(name, state)
end
# Get logging status for bucket
def logging
super(:bucket => name)
end
end
end