Getting started with S3 and Ruby on Rails

Why I’m using S3 with Rails…

The motivation for this at the moment is to use S3 as a backup for large image files posted on our gardening website which we don’t serve and to free up some disk space on our servers. We use file_column but that probably isn’t too relevant for this post. We don’t, at the moment, want to serve images from S3.

If you haven’t already implemented file upload and storage with Ruby on Rails you might still find this post useful but both attachment_fu and paperclip support S3 out of the box so you might want to look there.

Basic setup of S3 with Ruby…

First the obvious – set up an account with Amazon’s Web Services.

As instructed in the Intro to AWS for Ruby Developers I installed the S3 gem accepting all dependencies. You should specify the versions for each dependency if you need to know how to re-create your configuration…

$sudo gem install xml-simple --version 1.0.11
$sudo gem install builder --version 2.1.2
$sudo gem install mime-types --version 1.15
$sudo gem install aws-s3 --version 0.5.1

Or if you don’t care and just want to get it going…

$sudo gem install aws-s3

Before diving in to the code I did a quick test using the useful s3sh (like console but for s3) so start that up.

$s3sh

Then you’re ready to get started. I opened an S3 connection, created a bucket and put a file into my new bucket. Bucket names have to be globally unique, not unique to an account, like domain names .

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

=> #<AWS::S3::Connection:0x1588a44 @access_key_id="your key", @options={:persistent=>false, :server=>"s3.amazonaws.com", :port=>80, :access_key_id=>"your key", :secret_access_key=>"your secret key"}, @http=#<Net::HTTP s3.amazonaws.com:80 open=false>, @secret_access_key="your secret key">

>> Bucket.create('bucketname')
=> true
>>

>>AWS::S3::S3Object.store("bonsai.jpg", open("./Desktop/bonsai.jpg"), "bucketname", :access=>:public_read)
=> #<AWS::S3::S3Object::Response:0x11237200 200 OK>

Once I’d done that I put the url in the browser to check I could see the image (Note that if you configure the bucket in any way (e.g. you create a European bucket) it’s recommended (required?) you put the bucket name first in the URL. Bucket configuration is done when you create it so in the example above I did no configuration and can use…


If you do configure yours, use…

So, that was me with Amazon’s S3 installed and working, now on to getting it working with file_column but more about that later.

Advertisements

About this entry