Class: Module

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

Overview

Instance Method Summary collapse

Instance Method Details

#mattr_reader(*syms) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/attribute_accessors.rb', line 3

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_eval(<<-EOS, __FILE__, __LINE__ + 1)
      def #{sym}
        @@#{sym}
      end
    EOS
    class_variable_set("@@#{sym}", yield) if block_given?
  end
end