arbales
arbales

Reputation: 5536

Listing buckets with AWS::S3 in Sinatra

I'm trying to access my Amazon S3 account using the aws-s3 gem, but no matter what I do, I can't even print a bucket list.

Error:

undefined method `bytesize' for #<AWS::S3::Bucket:0x1b9e488>

From Code:

# hello_world.rb
require 'rubygems'
require 'sinatra'
require 'aws/s3'

get '/' do
  connection = AWS::S3::Base.establish_connection!(
     :access_key_id     => '***',
     :secret_access_key => '***'
   )
  AWS::S3::Service.buckets
end

I'm not too experienced with Ruby, am I just missing something obvious?

Upvotes: 2

Views: 2856

Answers (2)

Dan Sosedoff
Dan Sosedoff

Reputation: 2869

the problem is that you are trying to output the whole set of buckets, but there is no string serialization method, that's why you're getting this error.

Try this one:

app.rb

require 'rubygems'
require 'sinatra'
require 'aws/s3'

include AWS::S3

def s3_connect
  Base.establish_connection!(
    :access_key_id     => 'THISISMYACCESSKEYITMAYNOTBETHEBESTBUTITISMINE',
    :secret_access_key => 'HERPADERPSECRETKEYISSECRET'
  )
end

get '/' do
  s3_connect
  @buckets = Service.buckets
  erb :index
end

get '/bucket/:key' do
  s3_connect
  @bucket = Bucket.find(params[:key])
  erb :bucket
end

View: index.erb

<h1>Buckets</h1>
<ul>
  <% @buckets.each do |b| %>
    <li><a href='/bucket/<%= b.name %>'><%= b.name %></a> (<%= b.objects.length %> objects)</li>
  <% end %>
</ul>

View: bucket.erb

<h1>Bucket: <%= @bucket.name %> Objects</h1>
<% @bucket.objects.each do |obj| %>
  Object: <%= obj.key %> <%= obj.about['content-length'] %> bytes<br/>
<% end %>

Upvotes: 8

jrom
jrom

Reputation: 1960

You really should obfuscate your AWS secred_access_key before pasting it at stackoverflow, or at least change it now before somebody starts playing with your buckets...

Upvotes: 9

Related Questions