Module: Attributor::ExampleMixin

Defined in:
lib/attributor/example_mixin.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(obj) ⇒ Object



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

def self.extended(obj)
  if obj.is_a? 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



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

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

#[]=(k, v) ⇒ Object



33
34
35
36
# File 'lib/attributor/example_mixin.rb', line 33

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

#attributesObject



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

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

  super
end

#contentsObject



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

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



38
39
40
# File 'lib/attributor/example_mixin.rb', line 38

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

#empty?Boolean

Returns:



48
49
50
# File 'lib/attributor/example_mixin.rb', line 48

def empty?
  contents.empty?
end

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



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

def get(key, context: 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:



60
61
62
# File 'lib/attributor/example_mixin.rb', line 60

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

#keysObject



56
57
58
# File 'lib/attributor/example_mixin.rb', line 56

def keys
  @contents.keys | lazy_attributes.keys
end

#lazy_attributesObject



16
17
18
# File 'lib/attributor/example_mixin.rb', line 16

def lazy_attributes
  @lazy_attributes ||= {}
end

#lazy_attributes=(val) ⇒ Object



20
21
22
# File 'lib/attributor/example_mixin.rb', line 20

def lazy_attributes=(val)
  @lazy_attributes = val
end

#sizeObject



52
53
54
# File 'lib/attributor/example_mixin.rb', line 52

def size
  keys.size
end

#valuesObject



44
45
46
# File 'lib/attributor/example_mixin.rb', line 44

def values
  contents.values
end