Extends the module object with class/module and instance accessors for class/module attributes, just like the native attr* accessors for instance attributes.
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.
- MODULE Module::Concerning
- CLASS Module::DelegationError
- A
- C
- D
- M
- P
- R
- S
- T
[RW] | attr_internal_naming_format |
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
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
Declares an attribute reader and writer backed by an internally-named instance variable.
Declares an attribute reader backed by an internally-named instance variable.
Declares an attribute writer backed by an internally-named instance variable.
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 aModule::DelegationError
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 Module::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
# => Module::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)
@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
.
# File activesupport/lib/active_support/core_ext/module/delegation.rb, line 154 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 && /^[^a-z_]/.match?(to) 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.map do |method| # Attribute writer methods only accept one argument. Makes sure []= # methods still accept two arguments. definition = /[^\]]=$/.match?(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
When building decorators, a common pattern may emerge:
class Partition
def initialize(event)
@event = event
end
def person
@event.detail.person || @event.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 Module#delegate_missing_to
, the above is condensed to:
class Partition
delegate_missing_to :@event
def initialize(event)
@event = event
end
def person
@event.detail.person || @event.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
NoMethodError
.
# File activesupport/lib/active_support/core_ext/module/delegation.rb, line 258 def delegate_missing_to(target) target = target.to_s target = "self.#{target}" if DELEGATION_RESERVED_METHOD_NAMES.include?(target) module_eval <<-RUBY, __FILE__, __LINE__ + 1 def respond_to_missing?(name, include_private = false) # It may look like an oversight, but we deliberately do not pass # +include_private+, because they do not get delegated. #{target}.respond_to?(name) || super end def method_missing(method, *args, &block) if #{target}.respond_to?(method) #{target}.public_send(method, *args, &block) else begin super rescue NoMethodError if #{target}.nil? raise DelegationError, "\#{method} delegated to #{target}, but #{target} is nil" else raise end end end end RUBY end
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
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 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
You can set a default value for the attribute.
module HairColors
mattr_accessor :hair_colors, default: [:brown, :black, :blonde, :red]
end
class Person
include HairColors
end
Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
# File activesupport/lib/active_support/core_ext/module/attribute_accessors.rb, line 210 def mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil, &blk) mattr_reader(*syms, instance_reader: instance_reader, instance_accessor: instance_accessor, default: default, &blk) mattr_writer(*syms, instance_writer: instance_writer, instance_accessor: instance_accessor, default: default) end
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
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
You can set a default value for the attribute.
module HairColors
mattr_reader :hair_colors, default: [:brown, :black, :blonde, :red]
end
class Person
include HairColors
end
Person.new.hair_colors # => [:brown, :black, :blonde, :red]
# File activesupport/lib/active_support/core_ext/module/attribute_accessors.rb, line 54 def mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil) syms.each do |sym| raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym) class_eval(<<-EOS, __FILE__, __LINE__ + 1) @@#{sym} = nil unless defined? @@#{sym} def self.#{sym} @@#{sym} end EOS if instance_reader && instance_accessor class_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{sym} @@#{sym} end EOS end sym_default_value = (block_given? && default.nil?) ? yield : default class_variable_set("@@#{sym}", sym_default_value) unless sym_default_value.nil? end end
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]
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
You can set a default value for the attribute.
module HairColors
mattr_writer :hair_colors, default: [:brown, :black, :blonde, :red]
end
class Person
include HairColors
end
Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
# 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) syms.each do |sym| raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym) class_eval(<<-EOS, __FILE__, __LINE__ + 1) @@#{sym} = nil unless defined? @@#{sym} def self.#{sym}=(obj) @@#{sym} = obj end EOS if instance_writer && instance_accessor class_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{sym}=(obj) @@#{sym} = obj end EOS end sym_default_value = (block_given? && default.nil?) ? yield : default send("#{sym}=", sym_default_value) unless sym_default_value.nil? end end
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
Returns the name of the module containing this one.
M::N.parent_name # => "M"
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]
# File activesupport/lib/active_support/core_ext/module/introspection.rb, line 50 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
Replaces the existing method definition, if there is one, with the passed block as its body.
Replaces the existing singleton method definition, if there is one, with the passed block as its body.
Removes the named method, if it exists.
Removes the named singleton method, if it exists.
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 8 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
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