Module: Attributes

Included in:
Module
Defined in:
lib/attributes.rb,
lib/attributes-3.7.0.rb

Constant Summary collapse

VERSION =
'3.7.0'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.versionObject



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

def self.version() VERSION end

Instance Method Details

#attributes(*a, &b) ⇒ Object



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
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
# File 'lib/attributes.rb', line 5

def attributes *a, &b
  unless a.empty?
    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}

    names_and_defaults.each do |name, default|
      init = b || lambda { default }
      ivar, getter, setter, query, banger =
        "@#{ name }", "#{ name }", "#{ name }=", "#{ name }?", "#{ name }!"

      raise NameError, "bad instance variable name '#{ ivar }'" if ivar =~ %r/[!?=]$/o

      define_method(setter) do |value|
        __pervasive__('instance_variable_set', ivar, value)
      end

      define_method(getter) do |*value|
        unless value.empty?
          __pervasive__('send', setter, value.shift)
        else
          defined = __pervasive__('instance_variable_defined?', "#{ ivar }")
          __pervasive__('send', setter, __pervasive__('instance_eval', &init)) unless defined
          __pervasive__('instance_variable_get', ivar)
        end
      end

      define_method(banger) do
        __pervasive__('send', setter, __pervasive__('instance_eval', &init))
        __pervasive__('instance_variable_get', ivar)
      end

      alias_method query, getter

      (attributes << name.to_s).uniq!
      attributes
    end
  else
    begin
      __attribute_list__
    rescue NameError
      singleton_class =
        class << self
          self
        end
      klass = self
      singleton_class.module_eval do
        attribute_list = []
        define_method('attribute_list'){ klass == self ? attribute_list : raise(NameError) }
        alias_method '__attribute_list__', 'attribute_list'
      end
      __attribute_list__
    end
  end
end