1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/activesupport/lib/active_support/isolated_execution_state.rb
Jean Boussier 0ea374c81f Use IsolatedExecutionState across Active Support
Ref: https://github.com/rails/rails/pull/43596

This allow users to declare wether their unit of work is isolated by
fibers or by threads.

`PerThreadRegistry` and `thread_mattr_accessor` were intentionally left
out as they require documentation change. I'll submit them in separate
pull requests.
2021-11-19 09:58:15 +01:00

56 lines
1.2 KiB
Ruby

# frozen_string_literal: true
require "fiber"
module ActiveSupport
module IsolatedExecutionState # :nodoc:
@isolation_level = :thread
Thread.attr_accessor :active_support_execution_state
Fiber.attr_accessor :active_support_execution_state
class << self
attr_reader :isolation_level
def isolation_level=(level)
unless %i(thread fiber).include?(level)
raise ArgumentError, "isolation_level must be `:thread` or `:fiber`, got: `#{level.inspect}`"
end
if level != isolation_level
clear
singleton_class.alias_method(:current, "current_#{level}")
singleton_class.send(:private, :current)
@isolation_level = level
end
end
def unique_id
self[:__id__] ||= Object.new
end
def [](key)
current[key]
end
def []=(key, value)
current[key] = value
end
def clear
current.clear
end
private
def current_thread
Thread.current.active_support_execution_state ||= {}
end
def current_fiber
Fiber.current.active_support_execution_state ||= {}
end
alias_method :current, :current_thread
end
end
end