Module: Attributes

Included in:
Module
Defined in:
lib/bj/attributes.rb

Defined Under Namespace

Classes: List

Constant Summary collapse

VERSION =
'5.0.0'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.versionObject



3
# File 'lib/bj/attributes.rb', line 3

def self.version() Attributes::VERSION end

Instance Method Details

#attributes(*a, &b) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/bj/attributes.rb', line 26

def attributes *a, &b
  unless a.empty?
    returned = Hash.new

    hashes, names = a.partition{|x| Hash === x}
    names_and_defaults = {}
    hashes.each{|h| names_and_defaults.update h}
    names.flatten.compact.each{|name| names_and_defaults.update name => nil}

    initializers = __attributes__.initializers

    names_and_defaults.each do |name, default|
      raise NameError, "bad instance variable name '@#{ name }'" if "@#{ name }" =~ %r/[!?=]$/o
      name = name.to_s

      initialize = b || lambda { default }
      initializer = lambda do |this|
        Object.instance_method('instance_eval').bind(this).call &initialize
      end
      initializer_id = initializer.object_id
      __attributes__.initializers[name] = initializer

      module_eval <<-code
        def #{ name }=(*value, &block)
          value.unshift block if block
          @#{ name } = value.first
        end
      code

      module_eval <<-code
        def #{ name }(*value, &block)
          value.unshift block if block
          return self.send('#{ name }=', value.first) unless value.empty?
          #{ name }! unless defined? @#{ name }
          @#{ name }
        end
      code

      module_eval <<-code
        def #{ name }!
          initializer = ObjectSpace._id2ref #{ initializer_id }
          self.#{ name } = initializer.call(self)
          @#{ name }
        end
      code

      module_eval <<-code
        def #{ name }?
          #{ name }
        end
      code

      attributes << name
      returned[name] = initializer 
    end

    returned
  else
    begin
      __attribute_list__
    rescue NameError
      singleton_class =
        class << self
          self
        end
      klass = self
      singleton_class.module_eval do
        attribute_list = List.new 
        define_method('attribute_list'){ klass == self ? attribute_list : raise(NameError) }
        alias_method '__attribute_list__', 'attribute_list'
      end
      __attribute_list__
    end
  end
end