Skip to content

Instantly share code, notes, and snippets.

@jhjguxin
Created June 3, 2013 06:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jhjguxin/5696365 to your computer and use it in GitHub Desktop.
Save jhjguxin/5696365 to your computer and use it in GitHub Desktop.
cache devise's current_user method, speed up page's load, used for guanxi_cms, Suitable for devise 2.x - 3.x, Rails 3.x
class UserObserver < Mongoid::Observer
def after_save(record)
expire_cache(record)
end
private
def expire_cache(record)
Rails.cache.delete("user:#{record.id}")
end
end
# encoding: UTF-8
module Userable
extend ActiveSupport::Concern
included do
# super devise's `serialize_from_session`, which can cache current_user in session
# Suitable for devise 2.x - 3.x
# https://github.com/plataformatec/devise/blob/master/lib/devise/models/authenticatable.rb#L207
def self.serialize_from_session(key, salt)
single_key = key.is_a?(Array) ? key.first : key
record = Rails.cache.fetch("user:#{single_key}") { self.where(id: single_key).limit(1).first }
record if record && record.authenticatable_salt == salt
record.blank? ? super : record
end
end
# instance method
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment