Skip to content

Instantly share code, notes, and snippets.

@agibralter
Created October 2, 2008 15:11
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 agibralter/14374 to your computer and use it in GitHub Desktop.
Save agibralter/14374 to your computer and use it in GitHub Desktop.
class SessionModelProxy
attr_reader :session_data
def initialize(user, session_data, *args)
if session_data.is_a?(Hash)
@session_data = session_data
else
load_from_db(klass.find(id), args)
end
end
private
def load_from_db(obj, *attrs)
@klass = obj.class
@id = obj.id
@attrs = {}
(attrs << :id).uniq.each do |attribute|
@attrs[attribute.to_sym] = obj.send(attribute.to_sym)
end
@session_data = @attrs
end
def method_missing(method, *args, &block)
if @attrs[method.to_sym]
@attrs[method.to_sym]
else
@obj ||= @klass.find(@attrs[:id])
@obj.send(method, *args, &block)
load_from_db(@obj, @attrs.keys)
end
end
end
module AuthSystem
def current_user
@current_user ||= SessionModelProxy.new(User, session[:user])
end
def login_from_session
self.current_user = User.find_by_id(session[:user]) if session[:user]
end
def current_user=(new_user)
session[:user] = (new_user.nil? || new_user.is_a?(Symbol)) ? nil : new_user.id
@current_user = new_user
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment