Trevor Turk

A chess-playing machine of the late 18th century, promoted as an automaton but later proved a hoax.

Randomize Filename in Paperclip

Here's a quick tip that Jonathan Yurek, author of Paperclip, was kind enough to help me with. It's a simple way to have a randomized filename for uploaded content. This is useful for security through obscurity, especially when used with Paperclip's id_partition interpolation helper:
class Photo < Asset
  has_attached_file :image, :path => ":class/:attachment/:id_partition/:basename_:style.:extension"

  before_create :randomize_file_name


  def randomize_file_name
    extension = File.extname(image_file_name).downcase
    self.image.instance_write(:file_name, "#{ActiveSupport::SecureRandom.hex(16)}#{extension}")

That would, for example, change an uploaded image named "DS_100.JPG" into: That makes it effectively impossible to guess the location of an image, provided that you don't allow people to browse around the directories on your server. This is the same method of privacy protection that Flickr uses, and it ought to be enough for most non-governmental privacy needs :)

« Home page