Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mendelgusmao/4659230 to your computer and use it in GitHub Desktop.
Save mendelgusmao/4659230 to your computer and use it in GitHub Desktop.
Caching Dropbox URLs for paperclip-dropbox (not fully tested; not handling "missing" properly)
class AddAttachmentAvatarToUsers < ActiveRecord::Migration
def self.up
change_table :users do |t|
t.attachment :avatar
end
add_column :users, :avatar_dropbox, :string, :default => {}.to_yaml
end
def self.down
drop_attached_file :users, :avatar
remove_column :users, :avatar_dropbox
end
end
module ApplicationHelper
def dropbox_attachment_url(object, attribute, style = :original)
base = "#{attribute}_dropbox"
cache = object.send(base) || {}
cache[style] ||= {}
cache[style][:last_request] ||= Time.now - 4.hours
if Time.now - cache[style][:last_request] > 4.hours - 1.minute
attachment = object.send(attribute, style)
cache[style][:url] = attachment
cache[style][:last_request] = Time.now
object.update_attributes({base => cache})
cache[style][:url]
else
object.send(base)[style][:url]
end
end
end
class User < ActiveRecord::Base
serialize :avatar_dropbox
end
<%= tag(:img, { :src => dropbox_attachment_url(@user, :avatar) }, false) %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment