Timestamps with Paperclip and S3

I’m using Paperclip (2.3.11) to upload images to S3 and, as some other people have pointed out, if the content of a file changes but its name remains the same (for example, if you recrop the image), the timestamp added by Paperclip to the end of image URL won’t change. Consequently, the browser thinks the image hasn’t changed, and will display the old version.

Being image a Paperclip::Attachment, the url method will return something like:

> image.class
=> Paperclip::Attachment
> image.url
=> "http://domain/filename?1305625852"

If the image’s content changes, but not the name, the timestamp won’t change. To fix this issue, I’ve added a new and simple processor:

# config/initializers/paperclip_timestamper.rb
 
module Paperclip
  class TimeStamper < Processor
 
    def initialize(file, options={}, attachment=nil)
      super(file,options,attachment)
      timestamp_filename
    end
 
    def timestamp_filename
      attachment.instance_write(:updated_at, Time.now.to_i)
    end
 
    def make
      @file
    end
 
  end
end

Custom processors are currently not being loaded correctly in Rails 3 from lib/paperclip_processors, so a quick hack is to define it as a regular initializer. Don’t forget to specify the :processors option to has_attached_file:

has_couch_attached_file :image, ..., :processors => [:time_stamper]
This entry was posted in ruby. Bookmark the permalink.