Class: Odin::Serialization::Stringify

Inherits:
Object
  • Object
show all
Defined in:
lib/odin/serialization/stringify.rb

Defined Under Namespace

Classes: PathNode

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Stringify

Returns a new instance of Stringify.



14
15
16
17
18
19
20
# File 'lib/odin/serialization/stringify.rb', line 14

def initialize(options = {})
  @use_headers = options.fetch(:use_headers, true)
  @use_tabular = options.fetch(:use_tabular, true)
  @sort_paths  = options.fetch(:sort_paths, false)
  @line_ending = options.fetch(:line_ending, "\n")
  @include_comments = options.fetch(:include_comments, true)
end

Instance Method Details

#stringify(doc) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/odin/serialization/stringify.rb', line 22

def stringify(doc)
  lines = []

  # Get direct access to internal hashes — avoids method dispatch per path
  assignments = doc.assignments
   = doc.
  modifiers = doc.all_modifiers
  comments = @include_comments ? doc.all_comments : nil

  # Separate metadata and data paths
  meta_paths = []
  data_paths = []

  assignments.each_key do |path|
    if path.getbyte(0) == 36 && path.getbyte(1) == 46 # "$."
      meta_paths << path
    else
      data_paths << path
    end
  end

  # Also add from metadata map
  unless .empty?
    .each_key do |key|
      p = "$.#{key}"
      meta_paths << p unless assignments.key?(p)
    end
  end

  meta_paths.sort! if @sort_paths

  # Output metadata
  unless meta_paths.empty?
    lines << "{$}" if @use_headers
    meta_paths.each do |path|
      value = assignments[path] || [path[2..]]
      next unless value

      display_path = @use_headers ? path[2..] : path
      lines << format_assignment(display_path, value, modifiers[path], nil)
    end
    lines << "{}" if @use_headers && !data_paths.empty?
  end

  # Output data assignments
  if @use_headers && !@sort_paths && shallow_document?(data_paths)
    output_flat_sections(assignments, modifiers, comments, data_paths, lines)
  elsif @use_headers || @use_tabular
    output_hierarchical(assignments, modifiers, comments, data_paths, lines)
  else
    data_paths = data_paths.sort if @sort_paths
    data_paths.each do |path|
      value = assignments[path]
      next unless value

      comment = comments ? comments[path] : nil
      lines << format_assignment(path, value, modifiers[path], comment)
    end
  end

  result = lines.join(@line_ending)
  result << @line_ending unless lines.empty?
  result
end