module SentientUser

From github.com/bokmann/sentient_user

Public Class Methods

current() click to toggle source
# File lib/sentient_user/sentient_user.rb, line 6
def self.current
  Thread.current[:user]
end
current=(o) click to toggle source
# File lib/sentient_user/sentient_user.rb, line 10
def self.current=(o)
  raise(ArgumentError,
      "Expected an object of class '#{self}', got #{o.inspect}") unless (o.is_a?(self) || o.nil?)
  Thread.current[:user] = o
end
do_as(user, &block) click to toggle source
# File lib/sentient_user/sentient_user.rb, line 24
def self.do_as(user, &block)
  old_user = self.current

  begin
    self.current = user
    response = block.call unless block.nil?
  ensure
    self.current = old_user
  end

  response
end
included(base) click to toggle source
# File lib/sentient_user/sentient_user.rb, line 4
def self.included(base)
  base.class_eval {
    def self.current
      Thread.current[:user]
    end

    def self.current=(o)
      raise(ArgumentError,
          "Expected an object of class '#{self}', got #{o.inspect}") unless (o.is_a?(self) || o.nil?)
      Thread.current[:user] = o
    end

    def make_current
      Thread.current[:user] = self
    end

    def current?
      !Thread.current[:user].nil? && self.id == Thread.current[:user].id
    end
    
    def self.do_as(user, &block)
      old_user = self.current

      begin
        self.current = user
        response = block.call unless block.nil?
      ensure
        self.current = old_user
      end

      response
    end
  }
end

Public Instance Methods

current?() click to toggle source
# File lib/sentient_user/sentient_user.rb, line 20
def current?
  !Thread.current[:user].nil? && self.id == Thread.current[:user].id
end
make_current() click to toggle source
# File lib/sentient_user/sentient_user.rb, line 16
def make_current
  Thread.current[:user] = self
end