Class: Pvectl::Formatters::Json

Inherits:
Base
  • Object
show all
Defined in:
lib/pvectl/formatters/json.rb

Overview

Formats data as JSON output.

Collections are rendered as JSON arrays. Single resources are rendered as JSON objects. Empty collections return “[]”. Nil values are rendered as JSON null.

Examples:

JSON output for collection

[
  {"name": "vm-100", "status": "running"},
  {"name": "vm-101", "status": "stopped"}
]

JSON output for single resource

{"name": "vm-100", "status": "running", "node": "pve1"}

Instance Method Summary collapse

Instance Method Details

#format(data, presenter, color_enabled: true, describe: false, **context) ⇒ String

Formats data as JSON output.

Parameters:

  • data (Array, Object)

    collection of models or single model

  • presenter (Presenters::Base)

    presenter for hash conversion

  • color_enabled (Boolean) (defaults to: true)

    ignored for JSON (always plain text)

  • describe (Boolean) (defaults to: false)

    whether this is a describe command

  • context (Hash)

    ignored for JSON output

Returns:

  • (String)

    formatted JSON string (pretty-printed)



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/pvectl/formatters/json.rb', line 32

def format(data, presenter, color_enabled: true, describe: false, **context)
  if describe && !collection?(data)
    # Use to_description for describe mode
    JSON.pretty_generate(presenter.to_description(data))
  elsif collection?(data)
    hashes = data.map { |model| presenter.to_hash(model) }
    JSON.pretty_generate(hashes)
  else
    JSON.pretty_generate(presenter.to_hash(data))
  end
end