December 1, 2006

An Easy to use Amazon S3 Library for Ruby
Post from Peter Cooper

37signals code wizard Marcel Molina Jr has quietly released a library for accessing and manipulating Amazon S3 1 buckets. A project called s33r already existed, but Marcel's AWS::S3 library looks a lot simpler to use, and has a more Rails-esque feel.

Installation

You can easily install the library with gem install aws-s3

Note: The library comes with a command line prompt called s3sh which offers all of the same features in an irb esque fashion. This could be particularly useful for performing S3 maintenance, without specifically having Ruby in mind. S3 lacks a good command line client, so this is a great tool to check out.

Getting Started

Getting connected to S3 is a snap:

require 'aws/s3'

AWS::S3::Base.establish_connection!(
  :access_key_id     => 'key goes here',
  :secret_access_key => 'secret goes here'
)

Once connected, you can use several useful classes that represent some of the main S3 concepts.

Bucket represents the S3 buckets. You can use methods like find, create and objects to retrieve buckets, create new buckets or pluck an object directly out of a bucket.

S3Object represents an S3 object. This can be used to create and store an object on the server at the same time, as in this example:

S3Object.store(
  'name of object',
  File.open('large-picture.jpg'),
  'name of bucket',
  :content_type => 'image/jpeg'
)

You can even subclass S3Object so that your own classes can be used to make storing things in S3 simpler. Powerful ActiveRecord-style stuff.

Further Reading

Hopefully this brief overview has whet your appetite for hooking up Ruby and S3. I'm certainly pretty excited about this, as I couldn't get s33r working, and Marcel's library has a far simpler feel.

The best reference so far is the official documentation for AWS::S3 at http://amazon.rubyforge.org/.

1. Amazon S3 (standing for Simple Storage Service) is a remote storage system offered by Amazon.com. It costs $0.15 per gigabyte stored on their system per month, and $0.20 per gigabyte for any bandwidth used.