问题
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