Class: Fields::Serializer::FieldsTree

Inherits:
Object
  • Object
show all
Defined in:
lib/fields/serializer/fields_tree.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ FieldsTree

Returns a new instance of FieldsTree.



10
11
12
13
14
# File 'lib/fields/serializer/fields_tree.rb', line 10

def initialize(klass)
  @klass        = klass
  @fields       = []
  @associations = {}
end

Instance Attribute Details

#associationsObject (readonly)

Returns the value of attribute associations.



8
9
10
# File 'lib/fields/serializer/fields_tree.rb', line 8

def associations
  @associations
end

#fieldsObject (readonly)

Returns the value of attribute fields.



8
9
10
# File 'lib/fields/serializer/fields_tree.rb', line 8

def fields
  @fields
end

#klassObject (readonly)

Returns the value of attribute klass.



8
9
10
# File 'lib/fields/serializer/fields_tree.rb', line 8

def klass
  @klass
end

Instance Method Details

#merge!(join_field) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/fields/serializer/fields_tree.rb', line 20

def merge!(join_field)
  return self unless join_field.present?
  parent, rest = join_field.to_s.split(".", 2)
  if rest.blank?
    fields << parent if !(existing_field?(parent) || association?(parent))
  else
    existing_association?(parent) ? associations[parent].merge!(rest) : add_association!(parent, rest)
  end
  self
end

#notationObject



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/fields/serializer/fields_tree.rb', line 31

def notation
  if fields.present?
    if associations.present?
      fields.dup << associations_to_notation
    else
      fields.one? ? fields.first.dup : fields.dup
    end
  else
    associations_to_notation.presence
  end
end

#presenceObject



16
17
18
# File 'lib/fields/serializer/fields_tree.rb', line 16

def presence
  self if fields.present? || associations.present?
end

#to_includesObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/fields/serializer/fields_tree.rb', line 43

def to_includes
  to_includes = associations.inject([]) do |result, (k, v)|
    v_includes = v.to_includes
    if v_includes.present?
      new_has_entry = { k => v_includes }
      hash = result.find { |e| e.is_a?(Hash) }
      hash ? hash.merge!(new_has_entry) : (result << new_has_entry)
      result
    else
      result << k
    end
  end.presence
  Array.wrap(to_includes).one? ? to_includes.first : to_includes
end

#to_sObject



58
59
60
# File 'lib/fields/serializer/fields_tree.rb', line 58

def to_s
  notation.to_s
end