I'm starting to play around with Carrierwave , as an alternative to Paperclip .
I can see from the documentation that to use S3 I should configure Fog in a initializer:
CarrierWave.configure do |config|
config.fog_credentials = {
:provider => 'AWS', # required
:aws_access_key_id => 'xxx', # required
:aws_secret_access_key => 'yyy', # required
:region => 'eu-west-1' # optional, defaults to 'us-east-1'
}
end
However, how do I set up different buckets for different environments? With paperclip I would specify different credentials and/or buckets for development/production/etc in a yml file. What is the best way to do that with carrierwave?
You could do it pretty much exactly the same way if you want, like this entirely untested idea:
# config/initializers/carrierwave.rb
CarrierWave.configure do |config|
my_config = "#{Rails.root}/config/fog_credentials.yml"
YAML.load_file(my_config)[Rails.env].each do |key, val|
config.send("#{key}=", val)
end
end
# config/fog_credentials.yml
common: &common
aws_access_key: 'whatever'
...
fog_credentials:
provider: 'whoever'
...
production:
<<: *common
fog_directory: 'my-production-bucket'
development:
<<: *common
fog_directory: 'my-dev-bucket'
Or if you want to forego the YAML, you could always simply test for the environment in the initializer and use a case or conditional, at the simplest something like:
CarrierWave.configure.do |config|
if Rails.env.development?
# configure one env
else
# configure another
end
# configure common stuff
end
class S3ArticleUploader < CarrierWave::Uploader::Base
if Rails.env.test?
storage :file
else
storage :fog
end
def fog_directory
ARTICLE_UPLOADER_BUCKET
end
def store_dir
"#{ model.parent_id }/#{ model.id }"
end
end
# config/environments/development.rb
ARTICLE_UPLOADER_BUCKET = 'development-articles'
# config/environments/production.rb
ARTICLE_UPLOADER_BUCKET = 'production-articles'
fog_directory method calls when you are not in TestEnvironment and initializes the right BUCKET.
you can also do like this:
def store_dir
if self._storage == CarrierWave::Storage::File
"#{Rails.root}/tmp/files/#{ model.parent_id }/#{ model.id }"
elsif self._storage == CarrierWave::Storage::Fog
"#{ model.parent_id }/#{ model.id }"
end
end
class S3ArticleUploader < CarrierWave::Uploader::Base
if Rails.env.test?
storage :file
else
storage :fog
end
def initialize
self.fog_directory = ARTICLE_UPLOADER_BUCKET
end
def store_dir
"#{ model.parent_id }/#{ model.id }"
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.