An Easy Way to Rename Files with Attachment_fu

This is pretty simple, but I couldn’t find anything similar when I searched for it, so I’m posting in case it’s useful to someone else.

I’m using attachment_fu, the popular Rails file upload plugin, on a project where users upload photos. We needed to change the file names on upload so they wouldn’t contain any identifying information, and attachment_fu doesn’t have this functionality built in. Most of the discussion I found online covered changing the directory structure too, which is overkill here. I just need a simple way to change the names without accidentally clobbering some other part of the plugin’s functionality.

Here’s what I put in my image model, which has one thumbnail type (named “thumb”):

after_create :anonymize_name

def anonymize_name
  extension = filename.scan(/\.\w+$/)
  if thumbnail == "thumb"
    self.filename = "picture_#{parent_id}_thumb#{extension[0]}"
    self.filename = "picture_#{id}#{extension[0]}"

And that’s it.

As an aside, I discovered that there’s an attachment_fu rewrite in progress, which you can check out at, so that might be of interest to anyone looking to extend it further.

Comments are closed.