Method: Module#cattr

Defined in:
lib/core/facets/module/mattr.rb

#cattr(*syms) ⇒ Object

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

class CARExample
  @@a = 10
  cattr :a
end

CARExample.a           #=> 10
CARExample.new.a       #=> 10

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

CREDIT: David Heinemeier Hansson

Uncommon:

  • require ‘facets/module/cattr’



22
23
24
25
26
27
28
29
30
31
# File 'lib/core/facets/module/mattr.rb', line 22

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

  cattr_reader(*readers)
  cattr_writer(*writers)

  return readers + writers
end