Ruby Swift Examples

Create a Connection

This creates a connection so that you can interact with the server:

  1. require 'cloudfiles'
  2. username = 'account_name:user_name'
  3. api_key = 'your_secret_key'
  4. conn = CloudFiles::Connection.new(
  5. :username => username,
  6. :api_key => api_key,
  7. :auth_url => 'http://objects.dreamhost.com/auth'
  8. )

Create a Container

This creates a new container called my-new-container

  1. container = conn.create_container('my-new-container')

Create an Object

This creates a file hello.txt from the file named my_hello.txt

  1. obj = container.create_object('hello.txt')
  2. obj.load_from_filename('./my_hello.txt')
  3. obj.content_type = 'text/plain'

List Owned Containers

This gets a list of Containers that you own, and also prints out the container name:

  1. conn.containers.each do |container|
  2. puts container
  3. end

The output will look something like this:

  1. mahbuckat1
  2. mahbuckat2
  3. mahbuckat3

List a Container’s Contents

This gets a list of objects in the container, and prints out each object’s name, the file size, and last modified date:

  1. require 'date' # not necessary in the next version
  2. container.objects_detail.each do |name, data|
  3. puts "#{name}\t#{data[:bytes]}\t#{data[:last_modified]}"
  4. end

The output will look something like this:

  1. myphoto1.jpg 251262 2011-08-08T21:35:48.000Z
  2. myphoto2.jpg 262518 2011-08-08T21:38:01.000Z

Retrieve an Object

This downloads the object hello.txt and saves it in ./my_hello.txt:

  1. obj = container.object('hello.txt')
  2. obj.save_to_filename('./my_hello.txt')

Delete an Object

This deletes the object goodbye.txt:

  1. container.delete_object('goodbye.txt')

Delete a Container

Note

The container must be empty! Otherwise the request won’t work!

  1. container.delete_container('my-new-container')