class Module
def thread_mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil) # :nodoc:
Current.new.user # => NoMethodError
end
thread_mattr_reader :user, instance_reader: false
class Current
instance_reader: false or instance_accessor: false.
To omit the instance reader method, pass
# => NameError: invalid attribute name: 1_Badname
end
thread_mattr_reader :"1_Badname"
module Foo
The attribute name must be a valid method name in Ruby.
Thread.new { Current.user }.value # => nil
Current.user # => "DHH"
Current.user = "DHH"
end
thread_mattr_reader :user
module Current
The underlying per-thread class variable is set to +nil+, if it is not previously defined.
Defines a per-thread class attribute and creates class and instance reader methods.
def thread_mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil) # :nodoc: syms.each do |sym| raise NameError.new("invalid attribute name: #{sym}") unless /^[_A-Za-z]\w*$/.match?(sym) # The following generated method concatenates `name` because we want it # to work with inheritance via polymorphism. class_eval(<<-EOS, __FILE__, __LINE__ + 1) def self.#{sym} @__thread_mattr_#{sym} ||= "attr_\#{name}_#{sym}" ::ActiveSupport::IsolatedExecutionState[@__thread_mattr_#{sym}] end EOS if instance_reader && instance_accessor class_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{sym} self.class.#{sym} end EOS end ::ActiveSupport::IsolatedExecutionState["attr_#{name}_#{sym}"] = default unless default.nil? end end