Access Amazon S3 service through rails tasks.

This topic started 3 days ago and today I found one possible solution:
If you are working with Amazon S3 service and Ruby, you will have 2 gems to do all what you need.

aws-s3
aws-sdk

When you search through internet about amazon s3 and ruby you will find this link with a lot of info: amazon.rubyforge.org

This link uses the first gem aws-s3, and it works fine, but (we always have a “but”), if you are using paperclip to handle your files with S3, you need to add the second gem aws-sdk.

If you have both gems in your gemfile, you will see that you can’t use the info in amazon.rubyforge.org. 

Here was my big problem, this what I needed to do: check if a file is present in amazon s3 and upload inside a model in my rails application through a rails task.

Here is all info about aws-sdk: http://rubydoc.info/github/amazonwebservices/aws-sdk-for-ruby/master/AWS/S3

If you are using paperclip and s storage, you will have a s3.yml file with your config, and this is how you can connect to s3 storage:

s3 = AWS::S3.new( :access_key_id => ‘YOUR_ACCESS_KEY_ID’, :secret_access_key => ‘YOUR_SECRET_ACCESS_KEY’)

You can do something like this to get all data from your config file:

    # log requests using the default rails logger
    AWS.config(:logger => Rails.logger)
    # load credentials from a file
    config_path = File.expand_path(::Rails.root.to_s + “/config/s3.yml”)
    AWS.config(YAML.load(File.read(config_path)))

You can see that all WAS log info it will be redirected to Rails.logger, that is a good thing too.

After you have a connection, you need to get the Bucket where you will check if a file exists with this line:

current_bucket = AWS::S3::Bucket.find(S3Config[‘bucket’])

and you can check if a file is present there with this:

upload_bucket.objects[file_name].exists?

I found this info after look inside paperclip gem.
If you have any comment about this, please tell me.

Leave a Reply

Your email address will not be published. Required fields are marked *