Class: Module

Inherits:
Object show all
Includes:
Concerning
Defined in:
lib/active_support/core_ext/module/qualified_const.rb,
lib/active_support/core_ext/module/aliasing.rb,
lib/active_support/core_ext/module/anonymous.rb,
lib/active_support/core_ext/module/reachable.rb,
lib/active_support/core_ext/module/concerning.rb,
lib/active_support/core_ext/module/delegation.rb,
lib/active_support/core_ext/module/deprecation.rb,
lib/active_support/core_ext/module/attr_internal.rb,
lib/active_support/core_ext/module/introspection.rb,
lib/active_support/core_ext/module/remove_method.rb,
lib/active_support/core_ext/module/attribute_accessors.rb,
lib/active_support/core_ext/module/attribute_accessors_per_thread.rb

Overview

Extends the module object with class/module and instance accessors for class/module attributes, just like the native attr* accessors for instance attributes, but does so on a per-thread basis.

So the values are scoped within the Thread.current space under the class name of the module.

Defined Under Namespace

Modules: Concerning Classes: DelegationError

Constant Summary collapse

RUBY_RESERVED_KEYWORDS =
%w(alias and BEGIN begin break case class def defined? do
else elsif END end ensure false for if in module next nil not or redo rescue retry
return self super then true undef unless until when while yield)
DELEGATION_RESERVED_KEYWORDS =
%w(_ arg args block)
DELEGATION_RESERVED_METHOD_NAMES =
Set.new(
  RUBY_RESERVED_KEYWORDS + DELEGATION_RESERVED_KEYWORDS
).freeze

Class Attribute Summary collapse

Instance Method Summary collapse

Methods included from Concerning

#concern, #concerning

Class Attribute Details

.attr_internal_naming_formatObject

Returns the value of attribute attr_internal_naming_format.



20
21
22
# File 'lib/active_support/core_ext/module/attr_internal.rb', line 20

def attr_internal_naming_format
  @attr_internal_naming_format
end

Instance Method Details

#alias_attribute(new_name, old_name) ⇒ Object

Allows you to make aliases for attributes, which includes getter, setter, and a predicate.

class Content < ActiveRecord::Base
  # has a title attribute
end

class Email < Content
  alias_attribute :subject, :title
end

e = Email.find(1)
e.title    # => "Superstars"
e.subject  # => "Superstars"
e.subject? # => true
e.subject = "Megastars"
e.title    # => "Megastars"


67
68
69
70
71
72
73
# File 'lib/active_support/core_ext/module/aliasing.rb', line 67

def alias_attribute(new_name, old_name)
  module_eval <<-STR, __FILE__, __LINE__ + 1
    def #{new_name}; self.#{old_name}; end          # def subject; self.title; end
    def #{new_name}?; self.#{old_name}?; end        # def subject?; self.title?; end
    def #{new_name}=(v); self.#{old_name} = v; end  # def subject=(v); self.title = v; end
  STR
end

#alias_method_chain(target, feature) {|aliased_target, punctuation| ... } ⇒ Object

NOTE: This method is deprecated. Please use Module#prepend that comes with Ruby 2.0 or newer instead.

Encapsulates the common pattern of:

alias_method :foo_without_feature, :foo
alias_method :foo, :foo_with_feature

With this, you simply do:

alias_method_chain :foo, :feature

And both aliases are set up for you.

Query and bang methods (foo?, foo!) keep the same punctuation:

alias_method_chain :foo?, :feature

is equivalent to

alias_method :foo_without_feature?, :foo?
alias_method :foo?, :foo_with_feature?

so you can safely chain foo, foo?, foo! and/or foo= with the same feature.

Yields:

  • (aliased_target, punctuation)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/active_support/core_ext/module/aliasing.rb', line 26

def alias_method_chain(target, feature)
  ActiveSupport::Deprecation.warn("alias_method_chain is deprecated. Please, use Module#prepend instead. From module, you can access the original method using super.")

  # Strip out punctuation on predicates, bang or writer methods since
  # e.g. target?_without_feature is not a valid method name.
  aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
  yield(aliased_target, punctuation) if block_given?

  with_method = "#{aliased_target}_with_#{feature}#{punctuation}"
  without_method = "#{aliased_target}_without_#{feature}#{punctuation}"

  alias_method without_method, target
  alias_method target, with_method

  case
  when public_method_defined?(without_method)
    public target
  when protected_method_defined?(without_method)
    protected target
  when private_method_defined?(without_method)
    private target
  end
end

#anonymous?Boolean

A module may or may not have a name.

module M; end
M.name # => "M"

m = Module.new
m.name # => nil

anonymous? method returns true if module does not have a name, false otherwise:

Module.new.anonymous? # => true

module M; end
M.anonymous?          # => false

A module gets a name when it is first assigned to a constant. Either via the module or class keyword or by an explicit assignment:

m = Module.new # creates an anonymous module
m.anonymous?   # => true
M = m          # m gets a name here as a side-effect
m.name         # => "M"
m.anonymous?   # => false

Returns:

  • (Boolean)


25
26
27
# File 'lib/active_support/core_ext/module/anonymous.rb', line 25

def anonymous?
  name.nil?
end

#attr_internal_accessor(*attrs) ⇒ Object Also known as: attr_internal

Declares an attribute reader and writer backed by an internally-named instance variable.



14
15
16
17
# File 'lib/active_support/core_ext/module/attr_internal.rb', line 14

def attr_internal_accessor(*attrs)
  attr_internal_reader(*attrs)
  attr_internal_writer(*attrs)
end

#attr_internal_reader(*attrs) ⇒ Object

Declares an attribute reader backed by an internally-named instance variable.



3
4
5
# File 'lib/active_support/core_ext/module/attr_internal.rb', line 3

def attr_internal_reader(*attrs)
  attrs.each {|attr_name| attr_internal_define(attr_name, :reader)}
end

#attr_internal_writer(*attrs) ⇒ Object

Declares an attribute writer backed by an internally-named instance variable.



8
9
10
# File 'lib/active_support/core_ext/module/attr_internal.rb', line 8

def attr_internal_writer(*attrs)
  attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}
end

#delegate(*methods, to: nil, prefix: nil, allow_nil: nil) ⇒ Object

Provides a delegate class method to easily expose contained objects’ public methods as your own.

Options

  • :to - Specifies the target object

  • :prefix - Prefixes the new method with the target name or a custom prefix

  • :allow_nil - if set to true, prevents a NoMethodError from being raised

The macro receives one or more method names (specified as symbols or strings) and the name of the target object via the :to option (also a symbol or string).

Delegation is particularly useful with Active Record associations:

class Greeter < ActiveRecord::Base
  def hello
    'hello'
  end

  def goodbye
    'goodbye'
  end
end

class Foo < ActiveRecord::Base
  belongs_to :greeter
  delegate :hello, to: :greeter
end

Foo.new.hello   # => "hello"
Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>

Multiple delegates to the same target are allowed:

class Foo < ActiveRecord::Base
  belongs_to :greeter
  delegate :hello, :goodbye, to: :greeter
end

Foo.new.goodbye # => "goodbye"

Methods can be delegated to instance variables, class variables, or constants by providing them as a symbols:

class Foo
  CONSTANT_ARRAY = [0,1,2,3]
  @@class_array  = [4,5,6,7]

  def initialize
    @instance_array = [8,9,10,11]
  end
  delegate :sum, to: :CONSTANT_ARRAY
  delegate :min, to: :@@class_array
  delegate :max, to: :@instance_array
end

Foo.new.sum # => 6
Foo.new.min # => 4
Foo.new.max # => 11

It’s also possible to delegate a method to the class by using :class:

class Foo
  def self.hello
    "world"
  end

  delegate :hello, to: :class
end

Foo.new.hello # => "world"

Delegates can optionally be prefixed using the :prefix option. If the value is true, the delegate methods are prefixed with the name of the object being delegated to.

Person = Struct.new(:name, :address)

class Invoice < Struct.new(:client)
  delegate :name, :address, to: :client, prefix: true
end

john_doe = Person.new('John Doe', 'Vimmersvej 13')
invoice = Invoice.new(john_doe)
invoice.client_name    # => "John Doe"
invoice.client_address # => "Vimmersvej 13"

It is also possible to supply a custom prefix.

class Invoice < Struct.new(:client)
  delegate :name, :address, to: :client, prefix: :customer
end

invoice = Invoice.new(john_doe)
invoice.customer_name    # => 'John Doe'
invoice.customer_address # => 'Vimmersvej 13'

If the target is nil and does not respond to the delegated method a NoMethodError is raised, as with any other value. Sometimes, however, it makes sense to be robust to that situation and that is the purpose of the :allow_nil option: If the target is not nil, or it is and responds to the method, everything works as usual. But if it is nil and does not respond to the delegated method, nil is returned.

class User < ActiveRecord::Base
  has_one :profile
  delegate :age, to: :profile
end

User.new.age # raises NoMethodError: undefined method `age'

But if not having a profile yet is fine and should not be an error condition:

class User < ActiveRecord::Base
  has_one :profile
  delegate :age, to: :profile, allow_nil: true
end

User.new.age # nil

Note that if the target is not nil then the call is attempted regardless of the :allow_nil option, and thus an exception is still raised if said object does not respond to the method:

class Foo
  def initialize(bar)
    @bar = bar
  end

  delegate :name, to: :@bar, allow_nil: true
end

Foo.new("Bar").name # raises NoMethodError: undefined method `name'

The target method must be public, otherwise it will raise NoMethodError.



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/active_support/core_ext/module/delegation.rb', line 153

def delegate(*methods, to: nil, prefix: nil, allow_nil: nil)
  unless to
    raise ArgumentError, 'Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, to: :greeter).'
  end

  if prefix == true && to =~ /^[^a-z_]/
    raise ArgumentError, 'Can only automatically set the delegation prefix when delegating to a method.'
  end

  method_prefix = \
    if prefix
      "#{prefix == true ? to : prefix}_"
    else
      ''
    end

  location = caller_locations(1, 1).first
  file, line = location.path, location.lineno

  to = to.to_s
  to = "self.#{to}" if DELEGATION_RESERVED_METHOD_NAMES.include?(to)

  methods.each do |method|
    # Attribute writer methods only accept one argument. Makes sure []=
    # methods still accept two arguments.
    definition = (method =~ /[^\]]=$/) ? 'arg' : '*args, &block'

    # The following generated method calls the target exactly once, storing
    # the returned value in a dummy variable.
    #
    # Reason is twofold: On one hand doing less calls is in general better.
    # On the other hand it could be that the target has side-effects,
    # whereas conceptually, from the user point of view, the delegator should
    # be doing one call.
    if allow_nil
      method_def = [
        "def #{method_prefix}#{method}(#{definition})",
        "_ = #{to}",
        "if !_.nil? || nil.respond_to?(:#{method})",
        "  _.#{method}(#{definition})",
        "end",
      "end"
      ].join ';'
    else
      exception = %(raise DelegationError, "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")

      method_def = [
        "def #{method_prefix}#{method}(#{definition})",
        " _ = #{to}",
        "  _.#{method}(#{definition})",
        "rescue NoMethodError => e",
        "  if _.nil? && e.name == :#{method}",
        "    #{exception}",
        "  else",
        "    raise",
        "  end",
        "end"
      ].join ';'
    end

    module_eval(method_def, file, line)
  end
end

#deprecate(*method_names) ⇒ Object

deprecate :foo

deprecate bar: 'message'
deprecate :foo, :bar, baz: 'warning!', qux: 'gone!'

You can also use custom deprecator instance:

deprecate :foo, deprecator: MyLib::Deprecator.new
deprecate :foo, bar: "warning!", deprecator: MyLib::Deprecator.new

Custom deprecators must respond to deprecation_warning(deprecated_method_name, message, caller_backtrace) method where you can implement your custom warning behavior.

class MyLib::Deprecator
  def deprecation_warning(deprecated_method_name, message, caller_backtrace = nil)
    message = "#{deprecated_method_name} is deprecated and will be removed from MyLibrary | #{message}"
    Kernel.warn message
  end
end


20
21
22
# File 'lib/active_support/core_ext/module/deprecation.rb', line 20

def deprecate(*method_names)
  ActiveSupport::Deprecation.deprecate_methods(self, *method_names)
end

#local_constantsObject

:nodoc:



61
62
63
64
65
66
67
# File 'lib/active_support/core_ext/module/introspection.rb', line 61

def local_constants #:nodoc:
  ActiveSupport::Deprecation.warn(<<-MSG.squish)
    Module#local_constants is deprecated and will be removed in Rails 5.1.
    Use Module#constants(false) instead.
  MSG
  constants(false)
end

#mattr_accessor(*syms, &blk) ⇒ Object Also known as: cattr_accessor

Defines both class and instance accessors for class attributes.

module HairColors
  mattr_accessor :hair_colors
end

class Person
  include HairColors
end

HairColors.hair_colors = [:brown, :black, :blonde, :red]
HairColors.hair_colors # => [:brown, :black, :blonde, :red]
Person.new.hair_colors # => [:brown, :black, :blonde, :red]

If a subclass changes the value then that would also change the value for parent class. Similarly if parent class changes the value then that would change the value of subclasses too.

class Male < Person
end

Male.new.hair_colors << :blue
Person.new.hair_colors # => [:brown, :black, :blonde, :red, :blue]

To opt out of the instance writer method, pass instance_writer: false. To opt out of the instance reader method, pass instance_reader: false.

module HairColors
  mattr_accessor :hair_colors, instance_writer: false, instance_reader: false
end

class Person
  include HairColors
end

Person.new.hair_colors = [:brown]  # => NoMethodError
Person.new.hair_colors             # => NoMethodError

Or pass instance_accessor: false, to opt out both instance methods.

module HairColors
  mattr_accessor :hair_colors, instance_accessor: false
end

class Person
  include HairColors
end

Person.new.hair_colors = [:brown]  # => NoMethodError
Person.new.hair_colors             # => NoMethodError

Also you can pass a block to set up the attribute with a default value.

module HairColors
  mattr_accessor :hair_colors do
    [:brown, :black, :blonde, :red]
  end
end

class Person
  include HairColors
end

Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]


207
208
209
210
# File 'lib/active_support/core_ext/module/attribute_accessors.rb', line 207

def mattr_accessor(*syms, &blk)
  mattr_reader(*syms, &blk)
  mattr_writer(*syms)
end

#mattr_reader(*syms) ⇒ Object Also known as: cattr_reader

Defines a class attribute and creates a class and instance reader methods. The underlying class variable is set to nil, if it is not previously defined.

module HairColors
  mattr_reader :hair_colors
end

HairColors.hair_colors # => nil
HairColors.class_variable_set("@@hair_colors", [:brown, :black])
HairColors.hair_colors # => [:brown, :black]

The attribute name must be a valid method name in Ruby.

module Foo
  mattr_reader :"1_Badname"
end
# => NameError: invalid attribute name: 1_Badname

If you want to opt out the creation on the instance reader method, pass instance_reader: false or instance_accessor: false.

module HairColors
  mattr_reader :hair_colors, instance_reader: false
end

class Person
  include HairColors
end

Person.new.hair_colors # => NoMethodError

Also, you can pass a block to set up the attribute with a default value.

module HairColors
  mattr_reader :hair_colors do
    [:brown, :black, :blonde, :red]
  end
end

class Person
  include HairColors
end

Person.new.hair_colors # => [:brown, :black, :blonde, :red]


53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/active_support/core_ext/module/attribute_accessors.rb', line 53

def mattr_reader(*syms)
  options = syms.extract_options!
  syms.each do |sym|
    raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /\A[_A-Za-z]\w*\z/
    class_eval(<<-EOS, __FILE__, __LINE__ + 1)
      @@#{sym} = nil unless defined? @@#{sym}

      def self.#{sym}
        @@#{sym}
      end
    EOS

    unless options[:instance_reader] == false || options[:instance_accessor] == false
      class_eval(<<-EOS, __FILE__, __LINE__ + 1)
        def #{sym}
          @@#{sym}
        end
      EOS
    end
    class_variable_set("@@#{sym}", yield) if block_given?
  end
end

#mattr_writer(*syms) ⇒ Object Also known as: cattr_writer

Defines a class attribute and creates a class and instance writer methods to allow assignment to the attribute.

module HairColors
  mattr_writer :hair_colors
end

class Person
  include HairColors
end

HairColors.hair_colors = [:brown, :black]
Person.class_variable_get("@@hair_colors") # => [:brown, :black]
Person.new.hair_colors = [:blonde, :red]
HairColors.class_variable_get("@@hair_colors") # => [:blonde, :red]

If you want to opt out the instance writer method, pass instance_writer: false or instance_accessor: false.

module HairColors
  mattr_writer :hair_colors, instance_writer: false
end

class Person
  include HairColors
end

Person.new.hair_colors = [:blonde, :red] # => NoMethodError

Also, you can pass a block to set up the attribute with a default value.

module HairColors
  mattr_writer :hair_colors do
    [:brown, :black, :blonde, :red]
  end
end

class Person
  include HairColors
end

Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]


119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/active_support/core_ext/module/attribute_accessors.rb', line 119

def mattr_writer(*syms)
  options = syms.extract_options!
  syms.each do |sym|
    raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /\A[_A-Za-z]\w*\z/
    class_eval(<<-EOS, __FILE__, __LINE__ + 1)
      @@#{sym} = nil unless defined? @@#{sym}

      def self.#{sym}=(obj)
        @@#{sym} = obj
      end
    EOS

    unless options[:instance_writer] == false || options[:instance_accessor] == false
      class_eval(<<-EOS, __FILE__, __LINE__ + 1)
        def #{sym}=(obj)
          @@#{sym} = obj
        end
      EOS
    end
    send("#{sym}=", yield) if block_given?
  end
end

#method_visibility(method) ⇒ Object

:nodoc:



25
26
27
28
29
30
31
32
33
34
# File 'lib/active_support/core_ext/module/remove_method.rb', line 25

def method_visibility(method) # :nodoc:
  case
  when private_method_defined?(method)
    :private
  when protected_method_defined?(method)
    :protected
  else
    :public
  end
end

#parentObject

Returns the module which contains this one according to its name.

module M
  module N
  end
end
X = M::N

M::N.parent # => M
X.parent    # => M

The parent of top-level and anonymous modules is Object.

M.parent          # => Object
Module.new.parent # => Object


32
33
34
# File 'lib/active_support/core_ext/module/introspection.rb', line 32

def parent
  parent_name ? ActiveSupport::Inflector.constantize(parent_name) : Object
end

#parent_nameObject

Returns the name of the module containing this one.

M::N.parent_name # => "M"


7
8
9
10
11
12
13
14
15
# File 'lib/active_support/core_ext/module/introspection.rb', line 7

def parent_name
  if defined?(@parent_name)
    @parent_name
  else
    parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil
    @parent_name = parent_name unless frozen?
    parent_name
  end
end

#parentsObject

Returns all the parents of this module according to its name, ordered from nested outwards. The receiver is not contained within the result.

module M
  module N
  end
end
X = M::N

M.parents    # => [Object]
M::N.parents # => [M, Object]
X.parents    # => [M, Object]


48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/active_support/core_ext/module/introspection.rb', line 48

def parents
  parents = []
  if parent_name
    parts = parent_name.split('::')
    until parts.empty?
      parents << ActiveSupport::Inflector.constantize(parts * '::')
      parts.pop
    end
  end
  parents << Object unless parents.include? Object
  parents
end

#qualified_const_defined?(path, search_parents = true) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/active_support/core_ext/module/qualified_const.rb', line 29

def qualified_const_defined?(path, search_parents=true)
  ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
    Module#qualified_const_defined? is deprecated in favour of the builtin
    Module#const_defined? and will be removed in Rails 5.1.
  MESSAGE

  ActiveSupport::QualifiedConstUtils.raise_if_absolute(path)

  ActiveSupport::QualifiedConstUtils.names(path).inject(self) do |mod, name|
    return unless mod.const_defined?(name, search_parents)
    mod.const_get(name)
  end
  return true
end

#qualified_const_get(path) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/active_support/core_ext/module/qualified_const.rb', line 44

def qualified_const_get(path)
  ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
    Module#qualified_const_get is deprecated in favour of the builtin
    Module#const_get and will be removed in Rails 5.1.
  MESSAGE

  ActiveSupport::QualifiedConstUtils.raise_if_absolute(path)

  ActiveSupport::QualifiedConstUtils.names(path).inject(self) do |mod, name|
    mod.const_get(name)
  end
end

#qualified_const_set(path, value) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/active_support/core_ext/module/qualified_const.rb', line 57

def qualified_const_set(path, value)
  ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
    Module#qualified_const_set is deprecated in favour of the builtin
    Module#const_set and will be removed in Rails 5.1.
  MESSAGE

  ActiveSupport::QualifiedConstUtils.raise_if_absolute(path)

  const_name = path.demodulize
  mod_name = path.deconstantize
  mod = mod_name.empty? ? self : const_get(mod_name)
  mod.const_set(const_name, value)
end

#reachable?Boolean

:nodoc:

Returns:

  • (Boolean)


5
6
7
# File 'lib/active_support/core_ext/module/reachable.rb', line 5

def reachable? #:nodoc:
  !anonymous? && name.safe_constantize.equal?(self)
end

#redefine_method(method, &block) ⇒ Object

Replaces the existing method definition, if there is one, with the passed block as its body.



18
19
20
21
22
23
# File 'lib/active_support/core_ext/module/remove_method.rb', line 18

def redefine_method(method, &block)
  visibility = method_visibility(method)
  remove_possible_method(method)
  define_method(method, &block)
  send(visibility, method)
end

#remove_possible_method(method) ⇒ Object

Removes the named method, if it exists.



3
4
5
6
7
# File 'lib/active_support/core_ext/module/remove_method.rb', line 3

def remove_possible_method(method)
  if method_defined?(method) || private_method_defined?(method)
    undef_method(method)
  end
end

#remove_possible_singleton_method(method) ⇒ Object

Removes the named singleton method, if it exists.



10
11
12
13
14
# File 'lib/active_support/core_ext/module/remove_method.rb', line 10

def remove_possible_singleton_method(method)
  singleton_class.instance_eval do
    remove_possible_method(method)
  end
end

#thread_mattr_accessor(*syms, &blk) ⇒ Object Also known as: thread_cattr_accessor

Defines both class and instance accessors for class attributes.

class Account
  thread_mattr_accessor :user
end

Account.user = "DHH"
Account.user     # => "DHH"
Account.new.user # => "DHH"

If a subclass changes the value, the parent class’ value is not changed. Similarly, if the parent class changes the value, the value of subclasses is not changed.

class Customer < Account
end

Customer.user = "Rafael"
Customer.user # => "Rafael"
Account.user  # => "DHH"

To opt out of the instance writer method, pass instance_writer: false. To opt out of the instance reader method, pass instance_reader: false.

class Current
  thread_mattr_accessor :user, instance_writer: false, instance_reader: false
end

Current.new.user = "DHH"  # => NoMethodError
Current.new.user          # => NoMethodError

Or pass instance_accessor: false, to opt out both instance methods.

class Current
  mattr_accessor :user, instance_accessor: false
end

Current.new.user = "DHH"  # => NoMethodError
Current.new.user          # => NoMethodError


136
137
138
139
# File 'lib/active_support/core_ext/module/attribute_accessors_per_thread.rb', line 136

def thread_mattr_accessor(*syms, &blk)
  thread_mattr_reader(*syms, &blk)
  thread_mattr_writer(*syms, &blk)
end

#thread_mattr_reader(*syms) ⇒ Object Also known as: thread_cattr_reader

Defines a per-thread class attribute and creates class and instance reader methods. The underlying per-thread class variable is set to nil, if it is not previously defined.

module Current
  thread_mattr_reader :user
end

Current.user # => nil
Thread.current[:attr_Current_user] = "DHH"
Current.user # => "DHH"

The attribute name must be a valid method name in Ruby.

module Foo
  thread_mattr_reader :"1_Badname"
end
# => NameError: invalid attribute name: 1_Badname

If you want to opt out the creation on the instance reader method, pass instance_reader: false or instance_accessor: false.

class Current
  thread_mattr_reader :user, instance_reader: false
end

Current.new.user # => NoMethodError


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/active_support/core_ext/module/attribute_accessors_per_thread.rb', line 36

def thread_mattr_reader(*syms) # :nodoc:
  options = syms.extract_options!

  syms.each do |sym|
    raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
    class_eval(<<-EOS, __FILE__, __LINE__ + 1)
      def self.#{sym}
        Thread.current["attr_"+ name + "_#{sym}"]
      end
    EOS

    unless options[:instance_reader] == false || options[:instance_accessor] == false
      class_eval(<<-EOS, __FILE__, __LINE__ + 1)
        def #{sym}
          Thread.current["attr_"+ self.class.name + "_#{sym}"]
        end
      EOS
    end
  end
end

#thread_mattr_writer(*syms) ⇒ 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"

If you want to opt out 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


76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/active_support/core_ext/module/attribute_accessors_per_thread.rb', line 76

def thread_mattr_writer(*syms) # :nodoc:
  options = syms.extract_options!
  syms.each do |sym|
    raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
    class_eval(<<-EOS, __FILE__, __LINE__ + 1)
      def self.#{sym}=(obj)
        Thread.current["attr_"+ name + "_#{sym}"] = obj
      end
    EOS

    unless options[:instance_writer] == false || options[:instance_accessor] == false
      class_eval(<<-EOS, __FILE__, __LINE__ + 1)
        def #{sym}=(obj)
          Thread.current["attr_"+ self.class.name + "_#{sym}"] = obj
        end
      EOS
    end
  end
end