Module: Attributor::ExampleMixin

Defined in:
lib/attributor/example_mixin.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(obj) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/attributor/example_mixin.rb', line 8

def self.extended(obj)
  if obj.kind_of? Attributor::Model
    obj.class.attributes.each do |name, _|
      obj.define_singleton_method(name) do
        get(name)
      end
    end
  end
end

Instance Method Details

#[](k) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/attributor/example_mixin.rb', line 26

def [](k)
  unless @contents.key?(k)
    if (proc = lazy_attributes.delete k)
      @contents[k] = proc.call
    end
  end
  @contents[k]
end

#[]=(k, v) ⇒ Object



35
36
37
38
# File 'lib/attributor/example_mixin.rb', line 35

def []=(k,v)
  lazy_attributes.delete k
  @contents[k] = v
end

#attributesObject



79
80
81
82
83
84
85
# File 'lib/attributor/example_mixin.rb', line 79

def attributes
  lazy_attributes.keys.each do |name|
    self.__send__(name)
  end

  super
end

#contentsObject



87
88
89
90
91
92
93
94
# File 'lib/attributor/example_mixin.rb', line 87

def contents
  lazy_attributes.keys.each do |key|
    proc = lazy_attributes.delete(key)
    @contents[key] = proc.call(self) unless @contents.key?(key)
  end

  super
end

#each(&block) ⇒ Object Also known as: each_pair



40
41
42
# File 'lib/attributor/example_mixin.rb', line 40

def each(&block)
  contents.each(&block)
end

#empty?Boolean

Returns:



50
51
52
# File 'lib/attributor/example_mixin.rb', line 50

def empty?
  contents.empty?
end

#get(key, context: self.generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT,key)) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/attributor/example_mixin.rb', line 66

def get(key, context: self.generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT,key))
  key = self.class.key_attribute.load(key, context)

  unless @contents.key? key
    if lazy_attributes.key?(key)
      proc = lazy_attributes.delete(key)
      @contents[key] = proc.call(self)
    end
  end

  super
end

#key?(key) ⇒ Boolean

Returns:



62
63
64
# File 'lib/attributor/example_mixin.rb', line 62

def key?(key)
  @contents.key?(key) || lazy_attributes.key?(key)
end

#keysObject



58
59
60
# File 'lib/attributor/example_mixin.rb', line 58

def keys
  @contents.keys | lazy_attributes.keys
end

#lazy_attributesObject



18
19
20
# File 'lib/attributor/example_mixin.rb', line 18

def lazy_attributes
  @lazy_attributes ||= {}
end

#lazy_attributes=(val) ⇒ Object



22
23
24
# File 'lib/attributor/example_mixin.rb', line 22

def lazy_attributes=(val)
  @lazy_attributes = val
end

#sizeObject



54
55
56
# File 'lib/attributor/example_mixin.rb', line 54

def size
  keys.size
end

#valuesObject



46
47
48
# File 'lib/attributor/example_mixin.rb', line 46

def values
  contents.values
end