Method: Module#mattr
- Defined in:
- lib/core/facets/module/mattr.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 methiod is not a common core extension and is not loaded automatically when using require 'facets'.
CREDIT: David Heinemeier Hansson
162 163 164 165 166 167 168 169 170 171 |
# File 'lib/core/facets/module/mattr.rb', line 162 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 |