Tuesday 24 December 2013

Google Cloud Storage with Carrierwave/Mongoid (Rails 4.0)

Have just been creating a new Rails 4 app and am looking to use Google Cloud Storage for the first time. Previously I had been using Amazon S3

To upload images I'll be using carrierwave.

GemFile

# for image uploading
gem 'carrierwave'
gem "carrierwave-mongoid", git: "git://github.com/jnicklas/carrierwave-mongoid.git"
gem 'mongoid-grid_fs', github: 'ahoward/mongoid-grid_fs'
gem 'fog'
gem 'rmagick'

config/initializers/carrierwave.rb


require 'fog'
require 'rails'
require 'carrierwave'


CarrierWave.configure do |config|
  
  config.root = Rails.root.join('tmp')
  config.cache_dir = 'carrierwave'
  
  config.fog_credentials = {
    :provider                         => 'Google',
    :google_storage_access_key_id     => 'xxxxxx',
    :google_storage_secret_access_key => 'xxxxxx'
  }
  config.fog_directory = 'bucket_name'

end

Here's how to find the details you need:

app/uploaders/image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

  include Sprockets::Rails::Helper

  # Choose what kind of storage to use for this uploader:
  storage :fog

end
Important that you don't forget to include Sprockets::Rails::Helper in Rails 4+. Also, mongodb does not automatically save associated records so be sure to use cascade_callbacks or autosave options in your model depending on the relation - more info.

You should be good to go after this :)

No comments:

Post a Comment