Class: ViewModel::SerializeContext

Inherits:
TraversalContext show all
Defined in:
lib/view_model/serialize_context.rb

Defined Under Namespace

Classes: SharedContext

Instance Attribute Summary

Attributes inherited from TraversalContext

#shared_context

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from TraversalContext

#for_child, #for_references, #initialize, #initialize_as_child, #nearest_root, #nearest_root_viewmodel, new_child, #parent_association, #parent_context, #parent_ref, #parent_viewmodel, #root?, #run_callback

Constructor Details

This class inherits a constructor from ViewModel::TraversalContext

Class Method Details

.shared_context_classObject



17
18
19
# File 'lib/view_model/serialize_context.rb', line 17

def self.shared_context_class
  SharedContext
end

Instance Method Details

#extract_referenced_views!Object

Return viewmodels referenced during serialization and clear @references.



25
26
27
28
29
# File 'lib/view_model/serialize_context.rb', line 25

def extract_referenced_views!
  refs = references.each.to_h
  references.clear!
  refs
end

#serialize_references(json) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/view_model/serialize_context.rb', line 31

def serialize_references(json)
  reference_context = self.for_references

  # References should be serialized in a stable order to improve caching via
  # naive response hash.

  serialized_refs = {}

  while references.present?
    extract_referenced_views!.each do |ref, value|
      next if serialized_refs.has_key?(ref)

      serialized_refs[ref] = Jbuilder.new do |j|
        ViewModel.serialize(value, j, serialize_context: reference_context)
      end
    end
  end

  serialized_refs.sort.each do |ref, value|
    json.set!(ref, value)
  end
end

#serialize_references_to_hashObject



54
55
56
# File 'lib/view_model/serialize_context.rb', line 54

def serialize_references_to_hash
  Jbuilder.new { |json| serialize_references(json) }.attributes!
end