Module: Volt::ModelHashBehaviour

Included in:
Model
Defined in:
lib/volt/models/model_hash_behaviour.rb

Overview

Contains all of the methods on a model that make it behave like a hash. Moving this into a module cleans up the main Model class for things that make it behave like a model.

Instance Method Summary collapse

Instance Method Details

#clearObject



48
49
50
51
52
53
54
55
56
57
# File 'lib/volt/models/model_hash_behaviour.rb', line 48

def clear
  @attributes.each_pair do |key, _|
    delete(key)
  end

  # @attributes.clear
  @size_dep.changed!
  #
  # @persistor.removed(nil) if @persistor
end

#delete(name) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/volt/models/model_hash_behaviour.rb', line 6

def delete(name)
  name = name.to_sym

  value = @attributes.delete(name)

  @size_dep.changed!
  @deps.delete(name)

  @persistor.removed(name) if @persistor

  value
end

#each(&block) ⇒ Object



63
64
65
66
67
# File 'lib/volt/models/model_hash_behaviour.rb', line 63

def each(&block)
  # TODO: We shouldn't need to check the size for this to work
  size
  @array.each(&block)
end

#each_pairObject



69
70
71
72
73
# File 'lib/volt/models/model_hash_behaviour.rb', line 69

def each_pair
  @attributes.each_pair do |k, v|
    yield(k, v) unless v.is_a?(Model) && v.nil?
  end
end

#each_with_object(*args, &block) ⇒ Object



59
60
61
# File 'lib/volt/models/model_hash_behaviour.rb', line 59

def each_with_object(*args, &block)
  (@attributes || {}).each_with_object(*args, &block)
end

#empty?Boolean

Returns:



43
44
45
46
# File 'lib/volt/models/model_hash_behaviour.rb', line 43

def empty?
  @size_dep.depend
  !@attributes || @attributes.size == 0
end

#key?(key) ⇒ Boolean

Returns:



75
76
77
# File 'lib/volt/models/model_hash_behaviour.rb', line 75

def key?(key)
  @attributes && @attributes.key?(key)
end

#keysObject

Returns all of the keys, skipping over nil models TODO: We should store nil-models elsewhere so we don’t have to skip.



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/volt/models/model_hash_behaviour.rb', line 27

def keys
  @size_dep.depend

  keys = []

  each_pair do |k, v|
    keys << k
  end

  keys
end

#nil?Boolean

Returns:



39
40
41
# File 'lib/volt/models/model_hash_behaviour.rb', line 39

def nil?
  @attributes.nil?
end

#sizeObject



19
20
21
22
# File 'lib/volt/models/model_hash_behaviour.rb', line 19

def size
  @size_dep.depend
  @attributes.size
end

#to_hObject

Convert the model to a hash all of the way down.



80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/volt/models/model_hash_behaviour.rb', line 80

def to_h
  @size_dep.depend

  if @attributes.nil?
    nil
  else
    hash = {}
    @attributes.each_pair do |key, value|
      hash[key] = deep_unwrap(value)
    end
    hash
  end
end