Method: Module#thread_mattr_writer
- Defined in:
- activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb
#thread_mattr_writer(*syms, instance_writer: true, instance_accessor: true) ⇒ Object Also known as: thread_cattr_writer
Defines a per-thread class attribute and creates a class and instance writer methods to allow assignment to the attribute.
module Current
thread_mattr_writer :user
end
Current.user = "DHH"
Thread.current[:attr_Current_user] # => "DHH"
To omit the instance writer method, pass instance_writer: false or instance_accessor: false.
class Current
thread_mattr_writer :user, instance_writer: false
end
Current.new.user = "DHH" # => NoMethodError
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
# File 'activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb', line 101 def thread_mattr_writer(*syms, instance_writer: true, instance_accessor: true) # :nodoc: syms.each do |sym| raise NameError.new("invalid attribute name: #{sym}") unless /^[_A-Za-z]\w*$/.match?(sym) # The following generated method concatenates `object_id` because we want # subclasses to maintain independent values. class_eval(" def self.\#{sym}=(obj)\n @__thread_mattr_\#{sym} ||= \"attr_\#{sym}_\\\#{object_id}\"\n ::ActiveSupport::IsolatedExecutionState[@__thread_mattr_\#{sym}] = obj\n end\n EOS\n\n if instance_writer && instance_accessor\n class_eval(<<-EOS, __FILE__, __LINE__ + 1)\n def \#{sym}=(obj)\n self.class.\#{sym} = obj\n end\n EOS\n end\n end\nend\n", __FILE__, __LINE__ + 1) |