Paperclip, how to append a random stamp at the end of the file?

一曲冷凌霜 提交于 2019-12-08 07:03:30

You can use something like this to get the job done:

before_create :generate_random_hex

private
def generate_random_hex
  self.random_hex = ActiveSupport::SecureRandom.hex(8)
end

Paperclip.interpolates :random_hex do |attachment, style|
  attachment.instance.random_hex
end

Then modify your paperclip settings like so:

has_attached_file :photo,
  :styles => { :thumb => "70x70>" },
  :storage => :s3,
  :s3_credentials => "#{Rails.root}/config/s3.yml",
  :path => "/:rails_env/public/users/:id/:style/:basename_:random_hex.:extension",

Paperclip (now?) supports this out of the box:

has_attached_file :avatar,
    :styles => { :medium => "300x300>", :thumb => "100x100>"},
    :url => "/system/:id_partition/:style/:hash.:extension",
    :hash_secret => Test2::Application.config.secret_token

That way, the images are stored at /system/000/000/006/thumb/1c4fef2bf61f39193f8606521e880cbde54e04a1.jpg. Not short, though. With :basename you could add the basename to the url. See https://github.com/thoughtbot/paperclip#uri-obfuscation for more details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!