Module: Coradoc::CoreModel::FrontmatterBlock::Codec
- Defined in:
- lib/coradoc/core_model/frontmatter/codec.rb
Overview
Single source of truth for YAML ↔ FrontmatterBlock translation.
No other code in any gem may call YAML directly for frontmatter. This isolates permitted-classes configuration and error handling in one MECE location (DRY).
Constant Summary collapse
- PERMITTED_CLASSES =
[Date, Time, DateTime, Symbol].freeze
Class Method Summary collapse
-
.from_yaml(yaml_text) ⇒ Object
Parse a YAML string into a FrontmatterBlock.
-
.to_yaml(block) ⇒ Object
Serialize a FrontmatterBlock to canonical YAML text.
Class Method Details
.from_yaml(yaml_text) ⇒ Object
Parse a YAML string into a FrontmatterBlock. Returns an empty FrontmatterBlock on malformed YAML (graceful degradation — body parsing continues).
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/coradoc/core_model/frontmatter/codec.rb', line 20 def from_yaml(yaml_text) return FrontmatterBlock.new if yaml_text.nil? || yaml_text.strip.empty? parsed = YAML.safe_load( yaml_text, permitted_classes: PERMITTED_CLASSES, aliases: true ) return FrontmatterBlock.new unless parsed.is_a?(Hash) schema = parsed['$schema'] data = parsed.except('$schema') FrontmatterBlock.new(schema: schema&.to_s, data: data) rescue YAML::SyntaxError, Psych::DisallowedClass FrontmatterBlock.new end |
.to_yaml(block) ⇒ Object
Serialize a FrontmatterBlock to canonical YAML text. Does NOT include leading/trailing ‘—` delimiters; the caller wraps the output.
40 41 42 43 44 45 46 47 48 49 |
# File 'lib/coradoc/core_model/frontmatter/codec.rb', line 40 def to_yaml(block) return '' unless block.is_a?(FrontmatterBlock) tree = {} tree['$schema'] = block.schema if block.schema tree.merge!(block.data || {}) return '' if tree.empty? YAML.dump(tree).delete_prefix("---\n").delete_suffix("\n...") end |