Class: Module
Overview
Attribute Accessors per Thread
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.
Note that it can also be scoped per-fiber if Rails.application.config.active_support.isolation_level
is set to :fiber
.
Constant Summary
-
DelegationError =
Internal use only
# File 'activesupport/lib/active_support/core_ext/module/delegation.rb', line 5ActiveSupport::DelegationError
Class Attribute Summary
Instance Attribute Summary
-
#anonymous? ⇒ Boolean
readonly
A module may or may not have a name.
Instance Method Summary
-
#alias_attribute(new_name, old_name)
Allows you to make aliases for attributes, which includes getter, setter, and a predicate.
-
#attr_internal(*attrs)
Alias for #attr_internal_accessor.
-
#attr_internal_accessor(*attrs)
(also: #attr_internal)
Declares an attribute reader and writer backed by an internally-named instance variable.
-
#attr_internal_reader(*attrs)
Declares an attribute reader backed by an internally-named instance variable.
-
#attr_internal_writer(*attrs)
Declares an attribute writer backed by an internally-named instance variable.
-
#cattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil, &blk)
Alias for #mattr_accessor.
-
#cattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil, location: nil)
Alias for #mattr_reader.
-
#cattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil, location: nil)
Alias for #mattr_writer.
-
#deep_dup
Returns a copy of module or class if it’s anonymous.
-
#delegate(*methods, to: nil, prefix: nil, allow_nil: nil, private: nil)
Provides a #delegate class method to easily expose contained objects’ public methods as your own.
-
#delegate_missing_to(target, allow_nil: nil)
When building decorators, a common pattern may emerge:
-
#deprecate(*method_names, deprecator:, **options)
deprecate
:foo
, deprecator:MyLib.deprecator
-
#mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil, &blk)
(also: #cattr_accessor)
Defines both class and instance accessors for class attributes.
-
#mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil, location: nil)
(also: #cattr_reader)
Defines a class attribute and creates a class and instance reader methods.
-
#mattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil, location: nil)
(also: #cattr_writer)
Defines a class attribute and creates a class and instance writer methods to allow assignment to the attribute.
-
#module_parent
Returns the module which contains this one according to its name.
-
#module_parent_name
Returns the name of the module containing this one.
-
#module_parents
Returns all the parents of this module according to its name, ordered from nested outwards.
-
#redefine_method(method, &block)
Replaces the existing method definition, if there is one, with the passed block as its body.
-
#redefine_singleton_method(method, &block)
Replaces the existing singleton method definition, if there is one, with the passed block as its body.
-
#remove_possible_method(method)
Removes the named method, if it exists.
-
#remove_possible_singleton_method(method)
Removes the named singleton method, if it exists.
-
#silence_redefinition_of_method(method)
Marks the named method as intended to be redefined, if it exists.
-
#thread_cattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil)
Alias for #thread_mattr_accessor.
-
#thread_cattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil)
Alias for #thread_mattr_reader.
-
#thread_cattr_writer(*syms, instance_writer: true, instance_accessor: true)
Alias for #thread_mattr_writer.
-
#thread_mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil)
(also: #thread_cattr_accessor)
Defines both class and instance accessors for class attributes.
- #attr_internal_define(attr_name, type) private
- #as_json(options = nil) Internal use only
- #method_visibility(method) Internal use only
-
#thread_mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil)
(also: #thread_cattr_reader)
Internal use only
Defines a per-thread class attribute and creates class and instance reader methods.
-
#thread_mattr_writer(*syms, instance_writer: true, instance_accessor: true)
(also: #thread_cattr_writer)
Internal use only
Defines a per-thread class attribute and creates a class and instance writer methods to allow assignment to the attribute.
Concerning
- Included
#concern | A low-cruft shortcut to define a concern. |
#concerning | Define a new concern and mix it in. |
Class Attribute Details
.attr_internal_naming_format (rw)
[ GitHub ]# File 'activesupport/lib/active_support/core_ext/module/attr_internal.rb', line 23
attr_reader :attr_internal_naming_format
.attr_internal_naming_format=(format) (rw)
[ GitHub ]# File 'activesupport/lib/active_support/core_ext/module/attr_internal.rb', line 25
def attr_internal_naming_format=(format) if format.start_with?("@") raise ArgumentError, <<~MESSAGE.squish Setting `attr_internal_naming_format` with a `@` prefix is not supported. You can simply replace #{format.inspect} by #{format.delete_prefix("@").inspect}. MESSAGE end @attr_internal_naming_format = format end
Instance Attribute Details
#anonymous? ⇒ Boolean
(readonly)
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
# File 'activesupport/lib/active_support/core_ext/module/anonymous.rb', line 27
def anonymous? name.nil? end
Instance Method Details
#alias_attribute(new_name, old_name)
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"
# File 'activesupport/lib/active_support/core_ext/module/aliasing.rb', line 21
def alias_attribute(new_name, old_name) # The following reader methods use an explicit `self` receiver in order to # support aliases that start with an uppercase letter. Otherwise, they would # be resolved as constants instead. 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
#as_json(options = nil)
# File 'activesupport/lib/active_support/core_ext/object/json.rb', line 53
def as_json( = nil) # :nodoc: name end
#attr_internal(*attrs)
Alias for #attr_internal_accessor.
# File 'activesupport/lib/active_support/core_ext/module/attr_internal.rb', line 20
alias_method :attr_internal, :attr_internal_accessor
#attr_internal_accessor(*attrs) Also known as: #attr_internal
Declares an attribute reader and writer backed by an internally-named instance variable.
# File 'activesupport/lib/active_support/core_ext/module/attr_internal.rb', line 16
def attr_internal_accessor(*attrs) attr_internal_reader(*attrs) attr_internal_writer(*attrs) end
#attr_internal_define(attr_name, type) (private)
[ GitHub ]# File 'activesupport/lib/active_support/core_ext/module/attr_internal.rb', line 40
def attr_internal_define(attr_name, type) internal_name = Module.attr_internal_naming_format % attr_name # use native attr_* methods as they are faster on some Ruby implementations public_send("attr_#{type}", internal_name) attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer alias_method attr_name, internal_name remove_method internal_name end
#attr_internal_reader(*attrs)
Declares an attribute reader backed by an internally-named instance variable.
# File 'activesupport/lib/active_support/core_ext/module/attr_internal.rb', line 5
def attr_internal_reader(*attrs) attrs.each { |attr_name| attr_internal_define(attr_name, :reader) } end
#attr_internal_writer(*attrs)
Declares an attribute writer backed by an internally-named instance variable.
# File 'activesupport/lib/active_support/core_ext/module/attr_internal.rb', line 10
def attr_internal_writer(*attrs) attrs.each { |attr_name| attr_internal_define(attr_name, :writer) } end
#cattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil, &blk)
Alias for #mattr_accessor.
# File 'activesupport/lib/active_support/core_ext/module/attribute_accessors.rb', line 213
alias :cattr_accessor :mattr_accessor
#cattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil, location: nil)
Alias for #mattr_reader.
# File 'activesupport/lib/active_support/core_ext/module/attribute_accessors.rb', line 75
alias :cattr_reader :mattr_reader
#cattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil, location: nil)
Alias for #mattr_writer.
# File 'activesupport/lib/active_support/core_ext/module/attribute_accessors.rb', line 140
alias :cattr_writer :mattr_writer
#deep_dup
# File 'activesupport/lib/active_support/core_ext/object/deep_dup.rb', line 64
def deep_dup if name.nil? super else self end end
#delegate(*methods, to: nil, prefix: nil, allow_nil: nil, private: nil)
Provides a delegate
class method to easily expose contained objects’ public methods as your own.
Options
-
:to
- Specifies the target object name as a symbol or string -
:prefix
- Prefixes the new method with the target name or a custom prefix -
:allow_nil
- If set to true, prevents a::ActiveSupport::DelegationError
from being raised -
:private
- If set to true, changes method visibility to private
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'
The delegated methods are public by default. Pass private: true
to change that.
class User < ActiveRecord::Base
has_one :profile
delegate :first_name, to: :profile
delegate :date_of_birth, to: :profile, private: true
def age
Date.today.year - date_of_birth.year
end
end
User.new.first_name # => "Tomas"
User.new.date_of_birth # => NoMethodError: private method `date_of_birth' called for #<User:0x00000008221340>
User.new.age # => 2
If the target is nil
and does not respond to the delegated method a ::ActiveSupport::DelegationError
is raised. If you wish to instead return nil
, use the :allow_nil
option.
class User < ActiveRecord::Base
has_one :profile
delegate :age, to: :profile
end
User.new.age
# => ActiveSupport::DelegationError: User#age delegated to profile.age, but profile is nil
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 =
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
.
# File 'activesupport/lib/active_support/core_ext/module/delegation.rb', line 160
def delegate(*methods, to: nil, prefix: nil, allow_nil: nil, private: nil) ::ActiveSupport::Delegation.generate( self, methods, location: caller_locations(1, 1).first, to: to, prefix: prefix, allow_nil: allow_nil, private: private, ) end
#delegate_missing_to(target, allow_nil: nil)
When building decorators, a common pattern may emerge:
class Partition
def initialize(event)
@event = event
end
def person
detail.person || creator
end
private
def respond_to_missing?(name, include_private = false)
@event.respond_to?(name, include_private)
end
def method_missing(method, *args, &block)
@event.send(method, *args, &block)
end
end
With delegate_missing_to
, the above is condensed to:
class Partition
delegate_missing_to :@event
def initialize(event)
@event = event
end
def person
detail.person || creator
end
end
The target can be anything callable within the object, e.g. instance variables, methods, constants, etc.
The delegated method must be public on the target, otherwise it will raise ::ActiveSupport::DelegationError
. If you wish to instead return nil
, use the :allow_nil
option.
The marshal_dump
and _dump
methods are exempt from delegation due to possible interference when calling Marshal.dump(object)
, should the delegation target method of object
add or remove instance variables.
# File 'activesupport/lib/active_support/core_ext/module/delegation.rb', line 218
def delegate_missing_to(target, allow_nil: nil) ::ActiveSupport::Delegation.generate_method_missing( self, target, allow_nil: allow_nil, ) end
#deprecate(*method_names, deprecator:, **options)
deprecate :foo
, deprecator: MyLib.deprecator
deprecate :foo, bar: "warning!", deprecator: MyLib.deprecator
A deprecator is typically an instance of ::ActiveSupport::Deprecation
, but you can also pass any object that responds to deprecation_warning(deprecated_method_name, message, caller_backtrace)
where you can implement your custom warning behavior.
class MyLib::Deprecator
def deprecation_warning(deprecated_method_name, , caller_backtrace = nil)
= "#{deprecated_method_name} is deprecated and will be removed from MyLibrary | #{}"
Kernel.warn
end
end
# File 'activesupport/lib/active_support/core_ext/module/deprecation.rb', line 17
def deprecate(*method_names, deprecator:, ** ) if deprecator.is_a?(ActiveSupport::Deprecation) deprecator.deprecate_methods(self, *method_names, ** ) elsif deprecator # we just need any instance to call deprecate_methods, but the deprecation will be emitted by deprecator ActiveSupport.deprecator.deprecate_methods(self, *method_names, **, deprecator: deprecator) end end
#mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil, &blk) Also known as: #cattr_accessor
Defines both class and instance accessors for class attributes. All class and instance methods created will be public, even if this method is called with a private or protected access modifier.
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 Citizen < Person
end
Citizen.new.hair_colors << :blue
Person.new.hair_colors # => [:brown, :black, :blonde, :red, :blue]
To omit the instance writer method, pass instance_writer: false
. To omit 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 omit 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
You can set a default value for the attribute.
module HairColors
mattr_accessor :hair_colors, default: [:brown, :black, :blonde, :red]
mattr_accessor(:hair_styles) { [:long, :short] }
end
class Person
include HairColors
end
Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
Person.class_variable_get("@@hair_styles") # => [:long, :short]
# File 'activesupport/lib/active_support/core_ext/module/attribute_accessors.rb', line 208
def mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil, &blk) location = caller_locations(1, 1).first mattr_reader(*syms, instance_reader: instance_reader, instance_accessor: instance_accessor, default: default, location: location, &blk) mattr_writer(*syms, instance_writer: instance_writer, instance_accessor: instance_accessor, default: default, location: location) end
#mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil, location: nil) 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. All class and instance methods created will be public, even if this method is called with a private or protected access modifier.
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
To omit 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
You can set a default value for the attribute.
module HairColors
mattr_reader :hair_colors, default: [:brown, :black, :blonde, :red]
mattr_reader(:hair_styles) { [:long, :short] }
end
class Person
include HairColors
end
Person.new.hair_colors # => [:brown, :black, :blonde, :red]
Person.new.hair_styles # => [:long, :short]
# File 'activesupport/lib/active_support/core_ext/module/attribute_accessors.rb', line 55
def mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil, location: nil) raise TypeError, "module attributes should be defined directly on class, not singleton" if singleton_class? location ||= caller_locations(1, 1).first definition = [] syms.each do |sym| raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym) definition << "def self.#{sym}; @@#{sym}; end" if instance_reader && instance_accessor definition << "def #{sym}; @@#{sym}; end" end sym_default_value = (block_given? && default.nil?) ? yield : default class_variable_set("@@#{sym}", sym_default_value) unless sym_default_value.nil? && class_variable_defined?("@@#{sym}") end module_eval(definition.join(";"), location.path, location.lineno) end
#mattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil, location: nil) Also known as: #cattr_writer
Defines a class attribute and creates a class and instance writer methods to allow assignment to the attribute. All class and instance methods created will be public, even if this method is called with a private or protected access modifier.
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]
To omit 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
You can set a default value for the attribute.
module HairColors
mattr_writer :hair_colors, default: [:brown, :black, :blonde, :red]
mattr_writer(:hair_styles) { [:long, :short] }
end
class Person
include HairColors
end
Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
Person.class_variable_get("@@hair_styles") # => [:long, :short]
# File 'activesupport/lib/active_support/core_ext/module/attribute_accessors.rb', line 121
def mattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil, location: nil) raise TypeError, "module attributes should be defined directly on class, not singleton" if singleton_class? location ||= caller_locations(1, 1).first definition = [] syms.each do |sym| raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym) definition << "def self.#{sym}=(val); @@#{sym} = val; end" if instance_writer && instance_accessor definition << "def #{sym}=(val); @@#{sym} = val; end" end sym_default_value = (block_given? && default.nil?) ? yield : default class_variable_set("@@#{sym}", sym_default_value) unless sym_default_value.nil? && class_variable_defined?("@@#{sym}") end module_eval(definition.join(";"), location.path, location.lineno) end
#method_visibility(method)
# File 'activesupport/lib/active_support/core_ext/module/redefine_method.rb', line 30
def method_visibility(method) # :nodoc: case when private_method_defined?(method) :private when protected_method_defined?(method) :protected else :public end end
#module_parent
Returns the module which contains this one according to its name.
module M
module N
end
end
X = M::N
M::N.module_parent # => M
X.module_parent # => M
The parent of top-level and anonymous modules is ::Object
.
M.module_parent # => Object
Module.new.module_parent # => Object
# File 'activesupport/lib/active_support/core_ext/module/introspection.rb', line 34
def module_parent module_parent_name ? ActiveSupport::Inflector.constantize(module_parent_name) : Object end
#module_parent_name
Returns the name of the module containing this one.
M::N.module_parent_name # => "M"
# File 'activesupport/lib/active_support/core_ext/module/introspection.rb', line 9
def module_parent_name if defined?(@parent_name) @parent_name else parent_name = name =~ /::[^:]+\z/ ? -$` : nil @parent_name = parent_name unless frozen? parent_name end end
#module_parents
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.module_parents # => [Object]
M::N.module_parents # => [M, Object]
X.module_parents # => [M, Object]
# File 'activesupport/lib/active_support/core_ext/module/introspection.rb', line 50
def module_parents parents = [] if module_parent_name parts = module_parent_name.split("::") until parts.empty? parents << ActiveSupport::Inflector.constantize(parts * "::") parts.pop end end parents << Object unless parents.include? Object parents end
#redefine_method(method, &block)
Replaces the existing method definition, if there is one, with the passed block as its body.
# File 'activesupport/lib/active_support/core_ext/module/redefine_method.rb', line 17
def redefine_method(method, &block) visibility = method_visibility(method) silence_redefinition_of_method(method) define_method(method, &block) send(visibility, method) end
#redefine_singleton_method(method, &block)
Replaces the existing singleton method definition, if there is one, with the passed block as its body.
# File 'activesupport/lib/active_support/core_ext/module/redefine_method.rb', line 26
def redefine_singleton_method(method, &block) singleton_class.redefine_method(method, &block) end
#remove_possible_method(method)
Removes the named method, if it exists.
# File 'activesupport/lib/active_support/core_ext/module/remove_method.rb', line 7
def remove_possible_method(method) if method_defined?(method) || private_method_defined?(method) undef_method(method) end end
#remove_possible_singleton_method(method)
Removes the named singleton method, if it exists.
# File 'activesupport/lib/active_support/core_ext/module/remove_method.rb', line 14
def remove_possible_singleton_method(method) singleton_class.remove_possible_method(method) end
#silence_redefinition_of_method(method)
Marks the named method as intended to be redefined, if it exists. Suppresses the Ruby method redefinition warning. Prefer #redefine_method where possible.
# File 'activesupport/lib/active_support/core_ext/module/redefine_method.rb', line 7
def silence_redefinition_of_method(method) if method_defined?(method) || private_method_defined?(method) # This suppresses the "method redefined" warning; the self-alias # looks odd, but means we don't need to generate a unique name alias_method method, method end end
#thread_cattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil)
Alias for #thread_mattr_accessor.
# File 'activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb', line 174
alias :thread_cattr_accessor :thread_mattr_accessor
#thread_cattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil)
Alias for #thread_mattr_reader.
# File 'activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb', line 81
alias :thread_cattr_reader :thread_mattr_reader
#thread_cattr_writer(*syms, instance_writer: true, instance_accessor: true)
Alias for #thread_mattr_writer.
# File 'activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb', line 123
alias :thread_cattr_writer :thread_mattr_writer
#thread_mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil) 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"
Unlike #mattr_accessor, values are not shared with subclasses or parent classes. If a subclass changes the value, the parent class’ value is not changed. If the parent class changes the value, the value of subclasses is not changed.
class Customer < Account
end
Account.user # => "DHH"
Customer.user # => nil
Customer.user = "Rafael"
Customer.user # => "Rafael"
Account.user # => "DHH"
To omit the instance writer method, pass instance_writer: false
. To omit 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 omit both instance methods.
class Current
thread_mattr_accessor :user, instance_accessor: false
end
Current.new.user = "DHH" # => NoMethodError
Current.new.user # => NoMethodError
A default value may be specified using the :default
option. Because multiple threads can access the default value, non-frozen default values will be dup
ed and frozen.
# File 'activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb', line 170
def thread_mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil) thread_mattr_reader(*syms, instance_reader: instance_reader, instance_accessor: instance_accessor, default: default) thread_mattr_writer(*syms, instance_writer: instance_writer, instance_accessor: instance_accessor) end
#thread_mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil) 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 = "DHH"
Current.user # => "DHH"
Thread.new { Current.user }.value # => nil
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
To omit 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
# File 'activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb', line 41
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 `object_id` because we want # subclasses to maintain independent values. if default.nil? class_eval(<<-EOS, __FILE__, __LINE__ + 1) def self.#{sym} @__thread_mattr_#{sym} ||= "attr_#{sym}_\#{object_id}" ::ActiveSupport::IsolatedExecutionState[@__thread_mattr_#{sym}] end EOS else default = default.dup.freeze unless default.frozen? singleton_class.define_method("#{sym}_default_value") { default } class_eval(<<-EOS, __FILE__, __LINE__ + 1) def self.#{sym} @__thread_mattr_#{sym} ||= "attr_#{sym}_\#{object_id}" value = ::ActiveSupport::IsolatedExecutionState[@__thread_mattr_#{sym}] if value.nil? && !::ActiveSupport::IsolatedExecutionState.key?(@__thread_mattr_#{sym}) ::ActiveSupport::IsolatedExecutionState[@__thread_mattr_#{sym}] = #{sym}_default_value else value end end EOS end if instance_reader && instance_accessor class_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{sym} self.class.#{sym} end EOS end end end
#thread_mattr_writer(*syms, instance_writer: true, instance_accessor: true) 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
# 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(<<-EOS, __FILE__, __LINE__ + 1) def self.#{sym}=(obj) @__thread_mattr_#{sym} ||= "attr_#{sym}_\#{object_id}" ::ActiveSupport::IsolatedExecutionState[@__thread_mattr_#{sym}] = obj end EOS if instance_writer && instance_accessor class_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{sym}=(obj) self.class.#{sym} = obj end EOS end end end