Method: Module#mattr_reader

Defined in:
lib/oa_test/cattr.rb

#mattr_reader(*syms) ⇒ Object

Creates a class-variable attr_reader that can be accessed both on an instance and class level.

c = Class.new do
  @@a = 10
  mattr_reader :a
end

c.a           #=> 10
c.new.a       #=> 10

NOTE: This is not (presently) a common core extension and is not loaded automatically when using require 'facets'.

CREDIT: David Heinemeier Hansson



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/oa_test/cattr.rb', line 168

def mattr_reader( *syms )
  syms.flatten.each do |sym|
    module_eval(<<-EOS, __FILE__, __LINE__)
      unless defined? @@#{sym}
        @@#{sym} = nil
      end

      def self.#{sym}
        @@#{sym}
      end

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