Class: Module
- Inherits:
-
Object
- Object
- Module
- Defined in:
- lib/accessor_extender/module.rb
Overview
Extends the module object with class/module and instance accessors for class/module attributes, just like the native attr* accessors for instance attributes.
Instance Method Summary collapse
-
#mattr_accessor(*syms, &blk) ⇒ Object
(also: #cattr_accessor)
Defines both class and instance accessors for class attributes.
-
#mattr_reader(*syms) ⇒ Object
(also: #cattr_reader)
Defines a class attribute and creates a class and instance reader methods.
-
#mattr_writer(*syms) ⇒ Object
(also: #cattr_writer)
Defines a class attribute and creates a class and instance writer methods to allow assignment to the attribute.
Instance Method Details
#mattr_accessor(*syms, &blk) ⇒ Object Also known as: cattr_accessor
Defines both class and instance accessors for class attributes.
43 44 45 46 |
# File 'lib/accessor_extender/module.rb', line 43 def mattr_accessor(*syms, &blk) mattr_reader(*syms, &blk) mattr_writer(*syms, &blk) end |
#mattr_reader(*syms) ⇒ Object Also known as: cattr_reader
Defines a class attribute and creates a class and instance reader methods. The underlying the class variable is set to nil, if it is not previously defined.
10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/accessor_extender/module.rb', line 10 def mattr_reader(*syms) syms.each do |sym| raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/ class_eval(<<-EOS, __FILE__, __LINE__ + 1) @@#{sym} = nil unless defined? @@#{sym} def self.#{sym} @@#{sym} end EOS class_variable_set("@@#{sym}", yield) if block_given? end end |
#mattr_writer(*syms) ⇒ Object Also known as: cattr_writer
Defines a class attribute and creates a class and instance writer methods to allow assignment to the attribute.
27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/accessor_extender/module.rb', line 27 def mattr_writer(*syms) syms.each do |sym| raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/ class_eval(<<-EOS, __FILE__, __LINE__ + 1) @@#{sym} = nil unless defined? @@#{sym} def self.#{sym}=(obj) @@#{sym} = obj end EOS send("#{sym}=", yield) if block_given? end end |