Skip to content

Instantly share code, notes, and snippets.

@Tyralion
Created December 24, 2013 09:50
Show Gist options
  • Select an option

  • Save Tyralion/8111016 to your computer and use it in GitHub Desktop.

Select an option

Save Tyralion/8111016 to your computer and use it in GitHub Desktop.
# encoding: utf-8
module UserSession
extend self
USER_KEY = "user".freeze
SESSION_KEY = "session_id".freeze
class Rack
def initialize(app)
@app = app
@key = ::Rails.application.config.session_options[:key]
end # initialize
def call(env)
@request = ::Rack::Request.new(env)
register_user
@app.call(env)
end # call
private
def register_user
return unless changed?
@user_before = @request.session[::UserSession::USER_KEY]
@session_id_before = @request.session[::UserSession::SESSION_KEY]
::Thread.current[::UserSession::token] = (::User.auth_by_cookie(@request.session[::UserSession::USER_KEY]) || ::User.new)
nil
end # register_user
def changed?
return true if @user_before.nil?
return true if @user_before != @request.session[::UserSession::USER_KEY]
return true if @session_id_before != @request.session[::UserSession::SESSION_KEY]
false
end # changed?
end # Rack
def current
::Thread.current[::UserSession::token] || ::User.new
end # current
def token
::Anlas::Application.config.secret_token
end # token
end # UserSession
@Tyralion
Copy link
Author

В файле application.rb добавляем
config.middleware.use ::UserSession::Rack

Затем в любом месте проекта вызываем ::UserSession.current

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment