为开发存储图片本地,为生产使用S3,Rails Paperclip

21
我想在本地开发时上传图像,但在生产环境中将它们存储到我的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

这里有一些代码重复。

有没有一种方法可以在不重复代码的情况下编写它。

这是解决方案,非常感谢下面的Jordan和Andrey:

config / environments / development.rb

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

config/environment/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个回答

16

还有一种解决方案是将带参数的哈希移动到常量中,并在config/environments/*.rb文件中定义。然后你就可以使用:

has_attached_file :proto, PAPERCLIP_STORAGE_OPTS

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


哇,这是一个很好的想法。谢谢。我不知道该如何奖励你,因为我需要将你的答案与Jordan的答案结合起来。 - chell

15

当然可以。尝试做类似这样的事情:

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!代码块外,还需要注意在:convert_options中使用:all而不是三次指定相同选项的方式。


谢谢Jordan。我会按照你的建议去做,并结合上面的想法,以便摆脱unless语句。 - chell

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']
  }
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接