Class: Odin::Serialization::Stringify
- Inherits:
-
Object
- Object
- Odin::Serialization::Stringify
- Defined in:
- lib/odin/serialization/stringify.rb
Defined Under Namespace
Classes: PathNode
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ Stringify
constructor
A new instance of Stringify.
- #stringify(doc) ⇒ Object
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( = {}) @use_headers = .fetch(:use_headers, true) @use_tabular = .fetch(:use_tabular, true) @sort_paths = .fetch(:sort_paths, false) @line_ending = .fetch(:line_ending, "\n") @include_comments = .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 = [] data_paths = [] assignments.each_key do |path| if path.getbyte(0) == 36 && path.getbyte(1) == 46 # "$." << path else data_paths << path end end # Also add from metadata map unless .empty? .each_key do |key| p = "$.#{key}" << p unless assignments.key?(p) end end .sort! if @sort_paths # Output metadata unless .empty? lines << "{$}" if @use_headers .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 |