https://github.com/jnicklas/carrierwave
This example will create an uploader that will upload a file stored in a model Model. The file will be stored locally in development and test environment and will use Amazon S3 in production.
First add the gems.
# Gemfile
gem 'carrierwave'
gem 'fog'
Install gems.
bundle install
Generate uploader
rails generate uploader Model
Create model Model
rails generate model model file:string
rake db:migrate
Update the ModelUploader
# app/uploaders/model_uploader.rb
class ModelUploader < CarrierWave::Uploader::Base
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
Configure the model Model
# app/models/model.rb
class Model < ActiveRecord::Base
mount_uploader :file, ModelUploader
attr_accessible :file
end
Configure carrierwave to use Amazon S3. The AWS credentials that's needed in the config can be found here: https://portal.aws.amazon.com/gp/aws/securityCredentials#access_credentials and visit https://console.aws.amazon.com/s3/home# to setup a bucket.
# config/initializers/carrierwave.rb
# This file is not created by default so you might have to create it yourself.
CarrierWave.configure do |config|
# Use local storage if in development or test
if Rails.env.development? || Rails.env.test?
CarrierWave.configure do |config|
config.storage = :file
end
end
# Use AWS storage if in production
if Rails.env.production?
CarrierWave.configure do |config|
config.storage = :fog
end
end
config.fog_credentials = {
:provider => 'AWS', # required
:aws_access_key_id => '<your key goes here>', # required
:aws_secret_access_key => '<your secret key goes here>', # required
:region => 'eu-west-1' # optional, defaults to 'us-east-1'
}
config.fog_directory = '<bucket name goes here>' # required
#config.fog_host = 'https://assets.example.com' # optional, defaults to nil
#config.fog_public = false # optional, defaults to true
config.fog_attributes = {'Cache-Control'=>'max-age=315576000'} # optional, defaults to {}
end
# config/initializers/carrierwave.rb
module CarrierWave
module MiniMagick
def quality(percentage)
manipulate! do |img|
img.quality(percentage.to_s)
img = yield(img) if block_given?
img
end
end
end
end
# app/uploaders/my_uploader.rb
process :convert => 'png'
def filename
super.chomp(File.extname(super)) + '.png' if original_filename
end
# app/uploaders/my_uploader.rb
version :avatar, if: :create_avatar? do
process :resize_to_limit => [200, 200]
end
def create_avatar?(img = nil)
# conditions, return true / false
# e.g. model.should_create_avatar?
end
I solved the error, the problem was because I added the
config.fog_porvider = 'fog/amazon'
, check the issue of resolve the problem