Random File Name

16 views
Skip to first unread message

Florian

unread,
Dec 18, 2008, 2:39:46 PM12/18/08
to Paperclip Plugin
Hi!

First of all i would like to thank everybody involved for this
wonderful plugin!

In order to prevent users or bots to iterate over the uploaded images,
i would
like to name each image after a random key. e.g.
"jfrh8f3hr8f34fr939e929ke329rj49r.jpg"
I know that i can configure paperclip to rename images automatically
after upload,
but the renaming scheme seems to be static. Does anyone have an idea
how i could
assign a different random key for each uploaded image?

Thanks a lot!

Florian

Jonathan Yurek

unread,
Dec 18, 2008, 6:15:56 PM12/18/08
to papercli...@googlegroups.com
Hi,

If you're generating and saving the random name of the file in the
database you can add your own interpolation which can be used in urls
and paths.

Paperclip::Attachment.interpolations[:random_key] = lambda do |
attachment, style|
attachment.instance.random_key
end

:path => ":attachment/:style/:random_key.:extension"

... for example.

Hope that helps.
--
Jonathan Yurek, Founder and CTO
thoughtbot, inc.
organic brains. digital solutions.

617.482.1300 x114
http://www.thoughtbot.com/

Florian

unread,
Dec 18, 2008, 10:32:00 PM12/18/08
to Paperclip Plugin
Hi Jonathan!

works like a charm. That was exactly the hint i needed!
Keep up the good work!

Florian

Trevor Turk

unread,
Jan 5, 2009, 6:47:43 PM1/5/09
to Paperclip Plugin
On Dec 18 2008, 5:15 pm, Jonathan Yurek <jyu...@thoughtbot.com> wrote:
> If you're generating and saving therandomname of the file in the  
> database you can add your own interpolation which can be used in urls  
> and paths.

I'd been doing this with a before_create callback instead:

class Photo < ActiveRecord::Base
has_attached_file :image # ...

before_create :randomize_file_name

def randomize_file_name
extension = self.image_file_name.scan(/\.\w+$/).to_s.downcase
self.image_file_name = "#{CGI::Session.generate_unique_id}#
{extension}"
end
end

Not sure if this is better than the interpolation method, but it seems
to work well enough. Let me know if this stands out as a bad
technique, though!

- Trevor
Reply all
Reply to author
Forward
0 new messages