![](/img/trans.png)
[英]carrierwave uploads to s3 in development but not in production (heroku)
[英]Using different S3 buckets for production and development in Carrierwave
我開始玩Carrierwave ,作為Paperclip的替代品。
我可以從文檔中看到要使用S3我應該在初始化程序中配置Fog:
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
但是,如何為不同的環境設置不同的存儲桶? 使用回形針,我將在yml文件中為開發/生產/等指定不同的憑據和/或存儲桶。 使用carrierwave的最佳方法是什么?
如果你想要的話,你可以完全以同樣的方式做到這一點,就像這個完全沒有經過考驗的想法:
# 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'
或者如果你想放棄YAML,你總是可以在初始化程序中測試環境並使用case或條件,最簡單的方法是:
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'
當您不在TestEnvironment中並初始化正確的BUCKET時,fog_directory方法會調用。
你也可以這樣做:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.