Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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