Rails 3.2, Mongoid, Paperclip and Google Storage

If you're starting a Rails app from scratch I suggest using Rails Composer with the following command:

rails new your_app -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb -OT

During setup, choose Mongoid as your ORM as it's required. We pass -O and -T to skip ActiveRecord and replace Test::Unit with RSpec, respectively. The latter is not too important, so choose your own path there.

Choose the option to have Rails Composer create an application.yml file for configuring app-specific environment variables. It'll be helpful later on.

The next step is to sign up for Google Cloud Storage if you aren't already (and yes, it requires a Google Account). After this point, I'll assume you know enough about Ruby and Rails to execute the next steps.

In your Gemfile

gem "mongoid-paperclip"
gem "fog"

Then run $ bundle install.

Paperclip uses Fog as an API client to cloud storage services like Google Cloud Storage. However, it's not clear whether Paerclip integrates pieces of the Fog gem natively or if it relies solely on the Fog gem. It turned out to be the later.

In application.yml

Rails Composer gives you an application.yml file if you so choose. This is what you put in it.

GSTORAGE_HOST: http://yourbucketname.commondatastorage.googleapis.com
GSTORAGE_BUCKET: yourbucketname
GSTORAGE_ACCESS_KEY_ID: youraccesskey
GSTORAGE_SECRET_ACCESS_KEY: yoursecretaccesskey

Now we can call those variables like this ENV["GSTORAGE_BUCKET"] in application.rb. More on that next.

In application.rb

You can pass Paperclip some default values like so using our nifty environment variables:

module Yourapp
  class Application < Rails::Application       
    config.paperclip_defaults = {
      :storage => :fog,
      :fog_credentials => {
        :provider => "Google",
        :google_storage_access_key_id => ENV['GSTORAGE_ACCESS_KEY_ID'],
        :google_storage_secret_access_key => ENV['GSTORAGE_SECRET_ACCESS_KEY']
      },
      :fog_public => true,
      :fog_host => ENV['GSTORAGE_HOST'],
      :fog_directory => ENV['GSTORAGE_BUCKET']
    }
  end
end

Now you're set up to upload files to Google Cloud Storage. In the next part, I'll show you how to wire it up in controllers, mongoid documents and your views. You'll be surprised how simple it is.

February 28, 2013