Class: Docsmith::Rendering::JsonRenderer

Inherits:
Object
  • Object
show all
Defined in:
lib/docsmith/rendering/json_renderer.rb

Overview

Renders a DocumentVersion as a JSON export envelope.

One shape for every content_type. Before 0.2.0 this returned two incompatible schemas — a bare pretty-printed document for content_type "json", an envelope for everything else — so no client could parse it generically.

"content" is always the exact stored string, byte for byte. This is a versioning gem: an export that re-formatted the snapshot would not match what was versioned, and a client diffing two exports locally would get different results than the gem's own diff.

Pass include_parsed: true to additionally receive the parsed document under "data". That is the only code path that parses, so the default export cannot fail on malformed content.

Instance Method Summary collapse

Instance Method Details

#render(version, include_parsed: false, **_options) ⇒ String

Returns JSON representation of the version.

Parameters:

  • version (Docsmith::DocumentVersion)
  • include_parsed (Boolean) (defaults to: false)

    add "data" with the parsed document (json only)

Returns:

  • (String)

    JSON representation of the version



26
27
28
# File 'lib/docsmith/rendering/json_renderer.rb', line 26

def render(version, include_parsed: false, **_options)
  to_h(version, include_parsed: include_parsed).to_json
end

#to_h(version, include_parsed: false, **_options) ⇒ Hash

The canonical envelope, and the single source of truth for its shape.

author is emitted as type/id only. The gem cannot know the host app's author class, which fields it exposes, or which of them are personal data, so it never serializes the record itself.

Parameters:

Returns:

  • (Hash)

    string-keyed, JSON-ready

Raises:



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/docsmith/rendering/json_renderer.rb', line 40

def to_h(version, include_parsed: false, **_options)
  envelope = {
    "schema_version" => Docsmith::JSON_SCHEMA_VERSION,
    "document_id"    => version.document_id,
    "version_number" => version.version_number,
    "content_type"   => version.content_type.to_s,
    "content"        => version.content.to_s,
    "change_summary" => version.change_summary,
    "author"         => author_for(version),
    "metadata"       => version.,
    "created_at"     => version.created_at&.utc&.iso8601(3)
  }

  return envelope unless include_parsed && envelope["content_type"] == "json"

  envelope.merge("data" => parse(envelope["content"], version))
end