Class: Praxis::Handlers::JSON

Inherits:
Object
  • Object
show all
Defined in:
lib/praxis/handlers/json.rb

Instance Method Summary collapse

Constructor Details

#initializeJSON

Construct a JSON handler and initialize any related libraries.

Raises:



7
8
9
10
11
12
13
# File 'lib/praxis/handlers/json.rb', line 7

def initialize
  require 'json'
rescue LoadError
  # Should never happen since JSON is a default gem; might as well be cautious!
  raise Praxis::Exceptions::InvalidConfiguration,
        "JSON handler depends on json ~> 1.0; please add it to your Gemfile"
end

Instance Method Details

#generate(structured_data) ⇒ String

Generate a pretty-printed JSON document from structured data.

Parameters:

  • structured_data (Hash, Array)

Returns:

  • (String)


29
30
31
# File 'lib/praxis/handlers/json.rb', line 29

def generate(structured_data)
  ::JSON.pretty_generate(structured_data)
end

#parse(document) ⇒ Hash, Array

Parse a JSON document into structured data.

Parameters:

  • document (String)

Returns:

  • (Hash, Array)

    the structured-data representation of the document



19
20
21
22
23
# File 'lib/praxis/handlers/json.rb', line 19

def parse(document)
  # Try to be nice and accept an empty string as an empty payload (seems nice to do for dumb http clients)
  return nil if (document.nil? || document == '')
  ::JSON.parse(document)
end