Class: Leafy::FieldValueCollection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/leafy/field_value_collection.rb

Instance Method Summary collapse

Constructor Details

#initialize(leafy_fields, field_values: {}, ar_json: false) ⇒ FieldValueCollection

Returns a new instance of FieldValueCollection.



7
8
9
10
11
# File 'lib/leafy/field_value_collection.rb', line 7

def initialize(leafy_fields, field_values: {}, ar_json: false)
  @leafy_fields = leafy_fields
  @coder = ar_json ? Leafy::Coder::Mock.new : Leafy.configuration.coder
  self.leafy_field_values = field_values
end

Instance Method Details

#[](index) ⇒ Object



32
33
34
# File 'lib/leafy/field_value_collection.rb', line 32

def [](index)
  to_a[index]
end

#dumpObject



57
58
59
60
61
# File 'lib/leafy/field_value_collection.rb', line 57

def dump
  data = {}
  each { |field_value| data[field_value.id] = field_value.raw }
  @coder.dump(data)
end

#eachObject



24
25
26
27
28
29
30
# File 'lib/leafy/field_value_collection.rb', line 24

def each
  if block_given?
    @leafy_field_values.each { |i| yield i }
  else
    @leafy_field_values.each
  end
end

#leafy_field_values=(data) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/leafy/field_value_collection.rb', line 13

def leafy_field_values=(data)
  @leafy_field_values = @leafy_fields.map do |custom_field|
    Leafy::FieldValue.new(
      id: custom_field.id,
      name: custom_field.name,
      raw: data[custom_field.id],
      type: custom_field.type
    )
  end
end

#load(data) ⇒ Object



63
64
65
# File 'lib/leafy/field_value_collection.rb', line 63

def load(data)
  self.leafy_field_values = @coder.load(data)
end

#sizeObject



36
37
38
# File 'lib/leafy/field_value_collection.rb', line 36

def size
  count
end

#valuesObject



40
41
42
43
44
45
# File 'lib/leafy/field_value_collection.rb', line 40

def values
  inject({}) do |acc, field_value|
    acc[field_value.id] = field_value.value
    acc
  end
end

#values=(attributes = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/leafy/field_value_collection.rb', line 47

def values=(attributes = {})
  _attributes = {}

  attributes.each { |key, value| _attributes[key.to_s] = value }

  @leafy_field_values.each do |field_value|
    field_value.value = _attributes[field_value.id]
  end
end