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

限于喜欢 提交于 2020-01-14 04:35:08

问题


I'm using paperclip with my rails 3 app. I want to append a random string, nothing to long or crazy at the end of the file to cache bust the CDN. Anyone know a real simple way to do this?

Here is what I have currently:

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

I would like a file name like FILENAME_31313.png

Where 31313 is random every time a photo is saved.

Thank you


回答1:


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",



回答2:


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.



来源:https://stackoverflow.com/questions/7136473/paperclip-how-to-append-a-random-stamp-at-the-end-of-the-file

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