Friday 15 August 2014

Using Carrierwave and Fog

Following up installing RMagick in my previous post, I added Carrierwave and Fog. For the most part, instructions on getting Carrierwave running with Fog are in line with what I gathered in this blog post by JavaHabit. However, there's a few things to keep in mind:

  • Once you get your fog.rb generated, be sure to move it to your config/initializers folder.
  • If you plan on pushing your app to heroku, don't link your secret keys within the fog.rb file, you should install the dotenv-rails gem, make a .env file, put the keys inside it, then be sure to use ENV.fetch in the fog.rb file to obtain the keys remotely. Add .env to the gitignore file.
  • Restart your server. Additionally, it's best to convert the hash syntax within the fog.rb file to the newer rails style (if you use version 4).
  • Common error fixes: restart the server, remove the region line, and keep the fog.rb file to the bare minimum (delete mostlines to make most things set to their defaults). Those are the most common SO answers I've found.

Basically:

Add the dotenv-rails gem in your gemfile:

gem 'dotenv-rails'

In your fog.rb file, trim it down as much as possible and make the key hashes point to an ENV.fetch of the keys you need:

CarrierWave.configure do |config| 

config.fog_credentials = {
 provider: 'AWS',
 aws_access_key_id: ENV.fetch("AWS_ACCESS_KEY_ID"),
 aws_secret_access_key: ENV.fetch("AWS_SECRET_ACCESS_KEY"),
 }
 config.fog_directory = "bucketname"
 config.fog_attributes = {"Cache-Control'=>'max-age=315576000"}
end

In your .env file, make the following definitions for env variables:

AWS_ACCESS_KEY_ID=accesskey 
AWS_SECRET_ACCESS_KEY=secretaccesskey

In your gitignore file, add the uploads folder and .env to avoid uploading your images (if any) and secret keys onto github:

/public/uploads
.env

Lastly, in ImageUploader:

storage :fog

And that should set Fog up for your Carrierwave. Hope it helps!

No comments:

Post a Comment