File: active_support/core_ext/module/attribute_accessors.rb

Overview
Module Structure
Class Hierarchy
Code

Overview

Module Structure

  module: <Toplevel Module>
  module: <Built-in Module>
  class: Module#15
includes
  Module ( ActiveSupport::CoreExtensions )
  ClassMethods ( ActiveSupport::Deprecation )
inherits from
  Object ( Builtin-Module )
has properties
method: mattr_reader / 1 #16
method: mattr_writer / 1 #40
method: mattr_accessor / 1 #63

Class Hierarchy

Object ( Builtin-Module )
  Module    #15

Code

   1  require "active_support/core_ext/array"
   2 
   3  # Extends the module object with module and instance accessors for class attributes, 
   4  # just like the native attr* accessors for instance attributes.
   5  #
   6  #  module AppConfiguration
   7  #    mattr_accessor :google_api_key
   8  #    self.google_api_key = "123456789"
   9  #
  10  #    mattr_accessor :paypal_url
  11  #    self.paypal_url = "www.sandbox.paypal.com"
  12  #  end
  13  #
  14  #  AppConfiguration.google_api_key = "overriding the api key!"
  15  class Module
  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(<<-EOS, __FILE__, __LINE__ + 1)
  21          unless defined? @@#{sym}
  22            @@#{sym} = nil
  23          end
  24 
  25          def self.#{sym}
  26            @@#{sym}
  27          end
  28        EOS
  29 
  30        unless options[:instance_reader] == false
  31          class_eval(<<-EOS, __FILE__, __LINE__ + 1)
  32            def #{sym}
  33              @@#{sym}
  34            end
  35          EOS
  36        end
  37      end
  38    end
  39    
  40    def mattr_writer(*syms)
  41      options = syms.extract_options!
  42      syms.each do |sym|
  43        class_eval(<<-EOS, __FILE__, __LINE__ + 1)
  44          unless defined? @@#{sym}
  45            @@#{sym} = nil
  46          end
  47 
  48          def self.#{sym}=(obj)
  49            @@#{sym} = obj
  50          end
  51        EOS
  52 
  53        unless options[:instance_writer] == false
  54          class_eval(<<-EOS, __FILE__, __LINE__ + 1)
  55            def #{sym}=(obj)
  56              @@#{sym} = obj
  57            end
  58          EOS
  59        end
  60      end
  61    end
  62    
  63    def mattr_accessor(*syms)
  64      mattr_reader(*syms)
  65      mattr_writer(*syms)
  66    end
  67  end