Method: Module#cattr_writer

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

#cattr_writer(*syms) ⇒ Object

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

class CAWExample
  cattr_writer :a
  def self.a
    @@a
  end
end

CAWExample.a = 10
CAWExample.a            #=> 10
CAWExample.new.a = 29
CAWExample.a            #=> 29

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’



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/core/facets/module/mattr.rb', line 94

def cattr_writer(*syms)
  syms.flatten.each do |sym|
    module_eval("      unless defined? @@\#{sym}\n        @@\#{sym} = nil\n      end\n\n      def self.\#{sym}=(obj)\n        @@\#{sym} = obj\n      end\n\n      def \#{sym}=(obj)\n        @@\#{sym}=(obj)\n      end\n    EOS\n  end\n  return syms\nend\n", __FILE__, __LINE__)