Module: SentientUser

Defined in:
lib/sentient_user.rb,
lib/sentient_user/version.rb

Constant Summary collapse

VERSION =
"0.4.0"

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/sentient_user.rb', line 3

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