Created
June 3, 2013 06:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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