Module: Foreman::ThreadSession::UserModel

Included in:
User
Defined in:
lib/foreman/thread_session.rb

Overview

include this in the User model

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/foreman/thread_session.rb', line 41

def self.included(base)
  base.class_eval do
    def self.current
      Thread.current[:user]
    end

    def self.current=(o)
      unless o.nil? || o.is_a?(self)
        raise(ArgumentError, "Unable to set current User, expected class '#{self}', got #{o.inspect}")
      end

      Rails.logger.debug "Setting current user thread-local variable to " + (o.is_a?(User) ? o. : 'nil')
      Thread.current[:user] = o
    end

    # Executes given block on behalf of a different user. Example:
    #
    # User.as :admin do
    #   ...
    # end
    #
    # Use with care!
    #
    # @param [String] login to find from the database
    # @param [block] block to execute
    def self.as 
      old_user = current
      self.current = User.()
      yield if block_given?
    ensure
      self.current = old_user
    end
  end
end