Class: Class

Inherits:
Object
  • Object
show all
Defined in:
lib/support/cattr_accessor.rb

Overview

Extends the class object with class and instance accessors for class attributes, just like the native attr* accessors for instance attributes.

Instance Method Summary collapse

Instance Method Details

#cattr_accessor(*syms) ⇒ Object



53
54
55
56
# File 'lib/support/cattr_accessor.rb', line 53

def cattr_accessor(*syms)
  cattr_reader(*syms)
  cattr_writer(*syms)
end

#cattr_reader(*syms) ⇒ Object

:nodoc:



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/support/cattr_accessor.rb', line 4

def cattr_reader(*syms)
  syms.each do |sym|
    class_eval <<-EOS
      if ! defined? @@#{sym.id2name}
        @@#{sym.id2name} = nil
      end
      
      def self.#{sym.id2name}
        @@#{sym}
      end

      def #{sym.id2name}
        @@#{sym}
      end

      def call_#{sym.id2name}
        case @@#{sym.id2name}
          when Symbol then send(@@#{sym})
          when Proc   then @@#{sym}.call(self)
          when String then @@#{sym}
          else nil
        end
      end
    EOS
  end
end

#cattr_writer(*syms) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/support/cattr_accessor.rb', line 31

def cattr_writer(*syms)
  syms.each do |sym|
    class_eval <<-EOS
      if ! defined? @@#{sym.id2name}
        @@#{sym.id2name} = nil
      end
      
      def self.#{sym.id2name}=(obj)
        @@#{sym.id2name} = obj
      end

      def self.set_#{sym.id2name}(obj)
        @@#{sym.id2name} = obj
      end

      def #{sym.id2name}=(obj)
        @@#{sym} = obj
      end
    EOS
  end
end