开发者

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

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 =&g开发者_开发问答t; :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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜