Extends the module object with module and instance accessors for class attributes, just like the native attr* accessors for instance attributes.
module AppConfiguration mattr_accessor :google_api_key self.google_api_key = "123456789" mattr_accessor :paypal_url self.paypal_url = "www.sandbox.paypal.com" end AppConfiguration.google_api_key = "overriding the api key!"
- A
- D
- I
- M
- S
- ActiveSupport START:includes
- ActiveSupport START:includes
Returns String#underscore applied to the module name minus trailing classes.
ActiveRecord.as_load_path # => "active_record" ActiveRecord::Associations.as_load_path # => "active_record/associations" ActiveRecord::Base.as_load_path # => "active_record" (Base is a class)
The Kernel module gives an empty string by definition.
Kernel.as_load_path # => "" Math.as_load_path # => "math"
# File activesupport/lib/active_support/core_ext/module/loading.rb, line 12 12: def as_load_path 13: if self == Object || self == Kernel 14: '' 15: elsif is_a? Class 16: parent == self ? '' : parent.as_load_path 17: else 18: name.split('::').collect do |word| 19: word.underscore 20: end * '/' 21: end 22: end
Declare an attribute accessor with an initial default return value.
To give attribute :age the initial value 25:
class Person
attr_accessor_with_default :age, 25
end
some_person.age
=> 25
some_person.age = 26
some_person.age
=> 26
To give attribute :element_name a dynamic default value, evaluated in scope of self:
attr_accessor_with_default(:element_name) { name.underscore }
# File activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb, line 21 21: def attr_accessor_with_default(sym, default = nil, &block) 22: raise 'Default value or block required' unless !default.nil? || block 23: define_method(sym, block_given? ? block : Proc.new { default }) 24: module_eval("def \#{sym}=(value) # def age=(value)\nclass << self; attr_reader :\#{sym} end # class << self; attr_reader :age end\n@\#{sym} = value # @age = value\nend # end\n", __FILE__, __LINE__ + 1) 25: end
Alias for attr_internal_accessor
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’ methods as your own. Pass one or more methods (specified as symbols or strings) and the name of the target object as the final :to option (also a symbol or string). At least one method and the :to option are required.
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
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 object to which you delegate can be nil, you may want to use the :allow_nil option. In that case, it returns nil instead of raising a NoMethodError exception:
class Foo
attr_accessor :bar
def initialize(bar = nil)
@bar = bar
end
delegate :zoo, :to => :bar
end
Foo.new.zoo # raises NoMethodError exception (you called nil.zoo)
class Foo
attr_accessor :bar
def initialize(bar = nil)
@bar = bar
end
delegate :zoo, :to => :bar, :allow_nil => true
end
Foo.new.zoo # returns nil
# File activesupport/lib/active_support/core_ext/module/delegation.rb, line 99 99: def delegate(*methods) 100: options = methods.pop 101: unless options.is_a?(Hash) && to = options[:to] 102: raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)." 103: end 104: 105: if options[:prefix] == true && options[:to].to_s =~ /^[^a-z_]/ 106: raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method." 107: end 108: 109: prefix = options[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_" 110: 111: file, line = caller.first.split(':', 2) 112: line = line.to_i 113: 114: methods.each do |method| 115: on_nil = 116: if options[:allow_nil] 117: 'return' 118: else 119: %(raise "#{prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}") 120: end 121: 122: module_eval("def \#{prefix}\#{method}(*args, &block) # def customer_name(*args, &block)\n\#{to}.__send__(\#{method.inspect}, *args, &block) # client.__send__(:name, *args, &block)\nrescue NoMethodError # rescue NoMethodError\nif \#{to}.nil? # if client.nil?\n\#{on_nil}\nelse # else\nraise # raise\nend # end\nend # end\n", file, line) 123: end 124: end
Returns the classes in the current ObjectSpace where this module has been mixed in according to Module#included_modules.
module M
end
module N
include M
end
class C
include M
end
class D < C
end
p M.included_in_classes # => [C, D]
# File activesupport/lib/active_support/core_ext/module/inclusion.rb, line 21 21: def included_in_classes 22: classes = [] 23: ObjectSpace.each_object(Class) { |k| classes << k if k.included_modules.include?(self) } 24: 25: classes.reverse.inject([]) do |unique_classes, klass| 26: unique_classes << klass unless unique_classes.collect { |k| k.to_s }.include?(klass.to_s) 27: unique_classes 28: end 29: end
# File activesupport/lib/active_support/core_ext/module/attribute_accessors.rb, line 16 16: def mattr_reader(*syms) 17: options = syms.extract_options! 18: syms.each do |sym| 19: next if sym.is_a?(Hash) 20: class_eval("unless defined? @@\#{sym}\n@@\#{sym} = nil\nend\n\ndef self.\#{sym}\n@@\#{sym}\nend\n", __FILE__, __LINE__ + 1) 21: 22: unless options[:instance_reader] == false 23: class_eval("def \#{sym}\n@@\#{sym}\nend\n", __FILE__, __LINE__ + 1) 24: end 25: end 26: end
# File activesupport/lib/active_support/core_ext/module/attribute_accessors.rb, line 42 42: def mattr_writer(*syms) 43: options = syms.extract_options! 44: syms.each do |sym| 45: class_eval("unless defined? @@\#{sym}\n@@\#{sym} = nil\nend\n\ndef self.\#{sym}=(obj)\n@@\#{sym} = obj\nend\n", __FILE__, __LINE__ + 1) 46: 47: unless options[:instance_writer] == false 48: class_eval("def \#{sym}=(obj)\n@@\#{sym} = obj\nend\n", __FILE__, __LINE__ + 1) 49: end 50: end 51: end
Synchronize access around a method, delegating synchronization to a particular mutex. A mutex (either a Mutex, or any object that responds to synchronize and yields to a block) must be provided as a final :with option. The :with option should be a symbol or string, and can represent a method, constant, or instance or class variable. Example:
class SharedCache
@@lock = Mutex.new
def expire
...
end
synchronize :expire, :with => :@@lock
end
# File activesupport/lib/active_support/core_ext/module/synchronization.rb, line 15 15: def synchronize(*methods) 16: options = methods.extract_options! 17: unless options.is_a?(Hash) && with = options[:with] 18: raise ArgumentError, "Synchronization needs a mutex. Supply an options hash with a :with key as the last argument (e.g. synchronize :hello, :with => :@mutex)." 19: end 20: 21: methods.each do |method| 22: aliased_method, punctuation = method.to_s.sub(/([?!=])$/, ''), $1 23: 24: if method_defined?("#{aliased_method}_without_synchronization#{punctuation}") 25: raise ArgumentError, "#{method} is already synchronized. Double synchronization is not currently supported." 26: end 27: 28: module_eval("def \#{aliased_method}_with_synchronization\#{punctuation}(*args, &block) # def expire_with_synchronization(*args, &block)\n\#{with}.synchronize do # @@lock.synchronize do\n\#{aliased_method}_without_synchronization\#{punctuation}(*args, &block) # expire_without_synchronization(*args, &block)\nend # end\nend # end\n", __FILE__, __LINE__ + 1) 29: 30: alias_method_chain method, :synchronization 31: end 32: end