Module: Textus::Entry::Json
- Defined in:
- lib/textus/entry/json.rb
Overview
JSON entry storage. Top-level must be an object so we can carry _meta.
Class Method Summary collapse
- .extensions ⇒ Object
- .parse(raw, path: nil) ⇒ Object
- .serialize(meta:, body:, content: nil) ⇒ Object
Class Method Details
.extensions ⇒ Object
40 |
# File 'lib/textus/entry/json.rb', line 40 def self.extensions = [".json"] |
.parse(raw, path: nil) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/textus/entry/json.rb', line 7 def self.parse(raw, path: nil) raw = raw.dup.force_encoding(Encoding::UTF_8) raise BadFrontmatter.new(path, "entry is not valid UTF-8") unless raw.valid_encoding? begin parsed = ::JSON.parse(raw) rescue ::JSON::ParserError => e raise BadFrontmatter.new(path, "JSON parse failed: #{e.}") end raise BadFrontmatter.new(path, "JSON top-level must be an object") unless parsed.is_a?(Hash) = parsed["_meta"] fm = .is_a?(Hash) ? : {} = parsed.except("_meta") { "_meta" => fm, "body" => raw, "content" => } end |
.serialize(meta:, body:, content: nil) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/textus/entry/json.rb', line 24 def self.serialize(meta:, body:, content: nil) if content.is_a?(Hash) # Re-inject _meta as the first key so on-disk shape is stable. on_disk = && !.empty? ? { "_meta" => }.merge(content) : content out = ::JSON.pretty_generate(on_disk) out += "\n" unless out.end_with?("\n") out elsif body && !body.to_s.empty? b = body.to_s b += "\n" unless b.end_with?("\n") b else raise UsageError.new("json serialize requires :content or :body") end end |