Method: Module#mattr

Defined in:
lib/core-uncommon/facets/module/cattr.rb

#mattr(*syms) ⇒ Object

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

c = Class.new do
mattr :a
def initialize
  @@a = 10
end
end

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

NOTE: The #mattr methods may not be as useful for modules as the #cattr methods are for classes, becuase class-level methods are not "inherited" across the metaclass for included modules.

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

CREDIT: David Heinemeier Hansson



142
143
144
145
146
147
148
149
150
151
# File 'lib/core-uncommon/facets/module/cattr.rb', line 142

def mattr(*syms)
  writers, readers = syms.flatten.partition{ |a| a.to_s =~ /=$/ }
  writers = writers.collect{ |e| e.to_s.chomp('=').to_sym }
  ##readers.concat( writers ) # writers also get readers

  mattr_writer( *writers )
  mattr_reader( *readers )

  return readers + writers
end