Module: Foreman::ThreadSession::LocationModel

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

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object


114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/foreman/thread_session.rb', line 114

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

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

      Rails.logger.debug "Setting current location thread-local variable to #{location || "none"}"
      Thread.current[:location] = location
    end

    # Executes given block without the scope of a location:
    #
    # Location.as_location location do
    #   ...
    # end
    #
    # @param [location]
    # @param [block] block to execute
    def self.as_location location
      old_location = current
      self.current = location
      yield if block_given?
    ensure
      self.current = old_location
    end
  end
end