本地存储图像用于开发s3用于生产Rails Paperclip

时间:2011-11-15 05:17:22

标签: ruby-on-rails-3 paperclip

我想在我的本地计算机上上传图像以进行开发,但是将它们存储在我的Amazon S3帐户上进行生产。

upload.rb

if Rails.env.development?
  has_attached_file :photo, :styles => { :thumb => '40x40#', :medium => '150x200>', :large => '300x300>'},
                            :convert_options => { :thumb => "-quality 92", :medium => "-quality 92", :large => "-quality 92"  },
                            :processors => [:cropper]
else
  has_attached_file :photo, :styles => { :thumb => '40x40#', :medium => '150x200>', :large => '300x300>'},
                            :convert_options => { :thumb => "-quality 92", :medium => "-quality 92", :large => "-quality 92"  },
                            :storage => :s3,
                            :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
                            :path => ":attachment/:id/:style.:extension",
                            :bucket => 'birthdaywall_uploads',
                            :processors => [:cropper]
end

这里有一些代码重复。 有没有办法在没有代码重复的情况下编写它。

这是解决方案非常感谢乔丹和安德烈在下面:

配置/环境/ development.rb

   PAPERCLIP_STORAGE_OPTS = {
     :styles => { :thumb => '40x40#', :medium => '150x200>', :large => '300x300>' },
     :convert_options => { :all => '-quality 92' },
     :processor       => [ :cropper ]
   }

配置/环境/ production.rb

  PAPERCLIP_STORAGE_OPTS = {
    :styles => { :thumb => '40x40#', :medium => '150x200>', :large => '300x300>' },
    :convert_options => { :all => '-quality 92' },
    :storage        => :s3,
    :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
    :path           => ':attachment/:id/:style.:extension',
    :bucket         => 'birthdaywall_uploads',
    :processor       => [ :cropper ]
  }

3 个答案:

答案 0 :(得分:17)

另一个解决方案是将带有参数的散列移动到常量,这将在config / environments / * .rb文件中定义。然后你可以使用

has_attached_file :proto, PAPERCLIP_STORAGE_OPTS

在定义方法时使用if / unless在模型中有点混乱我认为

答案 1 :(得分:14)

不确定。尝试这样的事情:

paperclip_opts = {
  :styles => { :thumb => '40x40#', :medium => '150x200>', :large => '300x300>' },
  :convert_options => { :all => '-quality 92' },
  :processor       => [ :cropper ]
}

unless Rails.env.development?
  paperclip_opts.merge! :storage        => :s3,
                        :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
                        :path           => ':attachment/:id/:style.:extension',
                        :bucket         => 'birthdaywall_uploads',
end

has_attached_file :photo, paperclip_opts

除了显而易见的unless / merge!块之外,还要注意:all用于:convert_options,而不是指定三次相同的选项。

答案 2 :(得分:3)

为什么不在production.rb中修改paperclip默认选项?

将此添加到config / environments / production.rb:

Paperclip::Attachment.default_options.merge!({
  :storage => :s3,
  :bucket => 'bucketname',
  :s3_credentials => {
    :access_key_id => ENV['S3_ACCESS_KEY'],
    :secret_access_key => ENV['S3_SECRET_KEY']
  }
})