Class: YamlExporter::Exporter

Inherits:
Object
  • Object
show all
Defined in:
lib/yaml_exporter/exporter.rb

Overview

Walks a record + structure and emits the YAML document.

Key order follows declaration order of the structure's nodes. List order inside a many association is decided by the node itself.

omit_nil (an export-time option, passed from yaml_export) drops keys whose exported value is "empty": nil, or an empty list. This is round-trip safe because import treats a missing key, an explicit null, and an empty list identically. An owned child that exists but has only nil attributes exports as {} and is kept — omitting it would mean "destroy" on re-import.

Defined Under Namespace

Classes: BlockScalarTree

Instance Method Summary collapse

Constructor Details

#initialize(record, structure, omit_nil: true) ⇒ Exporter

Returns a new instance of Exporter.



37
38
39
40
41
# File 'lib/yaml_exporter/exporter.rb', line 37

def initialize(record, structure, omit_nil: true)
  @root_record = record
  @root_structure = structure
  @omit_nil = omit_nil
end

Instance Method Details

#build_hash(record, structure) ⇒ Object

Called recursively by nodes that own nested structures.



49
50
51
52
53
54
55
56
57
58
# File 'lib/yaml_exporter/exporter.rb', line 49

def build_hash(record, structure)
  result = {}
  structure.nodes.each do |node|
    key, value = node.export(record, exporter: self)
    next if @omit_nil && omit?(value)

    result[key] = value
  end
  result
end

#to_yamlObject



43
44
45
46
# File 'lib/yaml_exporter/exporter.rb', line 43

def to_yaml
  hash = build_hash(@root_record, @root_structure)
  dump(hash)
end