Sample Ruby Code Using DreamObjects OpenStack Swift-compatible API

Creating a Connection

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

require 'cloudfiles'
username = 'account_name:user_name'
api_key  = 'your_secret_key'

conn = CloudFiles::Connection.new(
        :username => username,
        :api_key  => api_key,
        :auth_url => 'http://objects-us-west-1.dream.io/auth'
)

Listing Owned Containers

This gets a list of Containers that you own. This also prints out the container name.

conn.containers.each do |container|
        puts container
end

The output will look something like this:

mahbuckat1
mahbuckat2
mahbuckat3

Creating a Container

This creates a new container called my-new-container

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

Listing a Container’s Content

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

require 'date'  # not necessary in the next version

container.objects_detail.each do |name, data|
        puts "#{name}\t#{data[:bytes]}\t#{data[:last_modified]}"
end

The output will look something like this:

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

Deleting a Container

Note

The Container must be empty! Otherwise it won’t work!

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

Creating an Object

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

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

Download an Object (to a file)

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

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

Delete an Object

This deletes the object goodbye.txt

container.delete_object('goodbye.txt')

Did this article answer your questions?

Article last updated .