Class: Module

Inherits:
Object show all
Includes:
ActiveSupport::CoreExtensions::Module, ActiveSupport::Deprecation::ClassMethods
Defined in:
lib/active_support/vendor/builder-2.1.2/blankslate.rb,
lib/active_support/deprecation.rb,
lib/active_support/core_ext/module.rb,
lib/active_support/core_ext/module/loading.rb,
lib/active_support/core_ext/module/inclusion.rb,
lib/active_support/core_ext/module/delegation.rb,
lib/active_support/core_ext/module/attr_internal.rb,
lib/active_support/core_ext/module/synchronization.rb,
lib/active_support/core_ext/module/attribute_accessors.rb,
lib/active_support/core_ext/module/attr_accessor_with_default.rb

Overview

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!"

Instance Method Summary collapse

Methods included from ActiveSupport::CoreExtensions::Module

#alias_attribute, #alias_method_chain, #local_constant_names, #local_constants, #model_name, #parent, #parent_name, #parents

Methods included from ActiveSupport::Deprecation::ClassMethods

#deprecate, #deprecated_method_warning, #deprecation_horizon

Instance Method Details

#append_features(mod) ⇒ Object


105
106
107
108
109
110
111
112
# File 'lib/active_support/vendor/builder-2.1.2/blankslate.rb', line 105

def append_features(mod)
  result = blankslate_original_append_features(mod)
  return result if mod != Object
  instance_methods.each do |name|
    BlankSlate.hide(name)
  end
  result
end

#as_load_pathObject

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"

12
13
14
15
16
17
18
19
20
21
22
# File 'lib/active_support/core_ext/module/loading.rb', line 12

def as_load_path
  if self == Object || self == Kernel
    ''
  elsif is_a? Class
    parent == self ? '' : parent.as_load_path
  else
    name.split('::').collect do |word|
      word.underscore
    end * '/'
  end
end

#attr_accessor_with_default(sym, default = nil, &block) ⇒ Object

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 }

21
22
23
24
25
26
27
28
29
30
# File 'lib/active_support/core_ext/module/attr_accessor_with_default.rb', line 21

def attr_accessor_with_default(sym, default = nil, &block)
  raise 'Default value or block required' unless !default.nil? || block
  define_method(sym, block_given? ? block : Proc.new { default })
  module_eval(<<-EVAL, __FILE__, __LINE__)
    def #{sym}=(value)
      class << self; attr_reader :#{sym} end
      @#{sym} = value
    end
  EVAL
end

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

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


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

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
6
7
# File 'lib/active_support/core_ext/module/attr_internal.rb', line 3

def attr_internal_reader(*attrs)
  attrs.each do |attr|
    module_eval "def #{attr}() #{attr_internal_ivar_name(attr)} end"
  end
end

#attr_internal_writer(*attrs) ⇒ Object

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


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

def attr_internal_writer(*attrs)
  attrs.each do |attr|
    module_eval "def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end"
  end
end

#blankslate_original_append_featuresObject


104
# File 'lib/active_support/vendor/builder-2.1.2/blankslate.rb', line 104

alias blankslate_original_append_features append_features

#delegate(*methods) ⇒ Object

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"

75
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/delegation.rb', line 75

def delegate(*methods)
  options = methods.pop
  unless options.is_a?(Hash) && to = options[: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 options[:prefix] == true && options[:to].to_s =~ /^[^a-z_]/
    raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method."
  end

  prefix = options[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_"

  methods.each do |method|
    module_eval(<<-EOS, "(__DELEGATION__)", 1)
      def #{prefix}#{method}(*args, &block)
        #{to}.__send__(#{method.inspect}, *args, &block)
      end
    EOS
  end
end

#included_in_classesObject

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]

21
22
23
24
25
26
27
28
29
# File 'lib/active_support/core_ext/module/inclusion.rb', line 21

def included_in_classes
  classes = []
  ObjectSpace.each_object(Class) { |k| classes << k if k.included_modules.include?(self) }

  classes.reverse.inject([]) do |unique_classes, klass| 
    unique_classes << klass unless unique_classes.collect { |k| k.to_s }.include?(klass.to_s)
    unique_classes
  end
end

#mattr_accessor(*syms) ⇒ Object


54
55
56
57
# File 'lib/active_support/core_ext/module/attribute_accessors.rb', line 54

def mattr_accessor(*syms)
  mattr_reader(*syms)
  mattr_writer(*syms)
end

#mattr_reader(*syms) ⇒ Object


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/active_support/core_ext/module/attribute_accessors.rb', line 14

def mattr_reader(*syms)
  syms.each do |sym|
    next if sym.is_a?(Hash)
    class_eval(<<-EOS, __FILE__, __LINE__)
      unless defined? @@#{sym}
        @@#{sym} = nil
      end
      
      def self.#{sym}
        @@#{sym}
      end

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

#mattr_writer(*syms) ⇒ Object


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/active_support/core_ext/module/attribute_accessors.rb', line 33

def mattr_writer(*syms)
  options = syms.extract_options!
  syms.each do |sym|
    class_eval(<<-EOS, __FILE__, __LINE__)
      unless defined? @@#{sym}
        @@#{sym} = nil
      end
      
      def self.#{sym}=(obj)
        @@#{sym} = obj
      end
      
      #{"
      def #{sym}=(obj)
        @@#{sym} = obj
      end
      " unless options[:instance_writer] == false }
    EOS
  end
end

#synchronize(*methods) ⇒ Object

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

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/active_support/core_ext/module/synchronization.rb', line 15

def synchronize(*methods)
  options = methods.extract_options!
  unless options.is_a?(Hash) && with = options[:with]
    raise ArgumentError, "Synchronization needs a mutex. Supply an options hash with a :with key as the last argument (e.g. synchronize :hello, :with => :@mutex)."
  end

  methods.each do |method|
    aliased_method, punctuation = method.to_s.sub(/([?!=])$/, ''), $1

    if method_defined?("#{aliased_method}_without_synchronization#{punctuation}")
      raise ArgumentError, "#{method} is already synchronized. Double synchronization is not currently supported."
    end

    module_eval(<<-EOS, __FILE__, __LINE__)
      def #{aliased_method}_with_synchronization#{punctuation}(*args, &block)
        #{with}.synchronize do
          #{aliased_method}_without_synchronization#{punctuation}(*args, &block)
        end
      end
    EOS

    alias_method_chain method, :synchronization
  end
end