Sha256: 2eba298665f1782cc52b79b413ad8cfd25bebfa2b2e4601a8fddc7f2094afe23

Contents?: true

Size: 1.4 KB

Versions: 13

Compression:

Stored size: 1.4 KB

Contents

# frozen_string_literal: true

module Praxis
  module Handlers
    class JSON
      # Construct a JSON handler and initialize any related libraries.
      #
      # @raise [Praxis::Exceptions::InvalidConfiguration] if the handler is unsupported
      def initialize
        require 'oj'
        begin
          require 'json'
        rescue LoadError # rubocop:disable Lint/SuppressedException
        end
        # Enable mimicing needs to be done after loading the JSON gem (if there)
        ::Oj.mimic_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 oj ~> 3; please add it to your Gemfile'
      end

      # Parse a JSON document into structured data.
      #
      # @param [String] document
      # @return [Hash,Array] the structured-data representation of the document
      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 == ''

        ::Oj.load(document)
      end

      # Generate a pretty-printed JSON document from structured data.
      #
      # @param [Hash,Array] structured_data
      # @return [String]
      def generate(structured_data)
        ::Oj.dump(structured_data, indent: 2)
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
praxis-2.0.pre.37 lib/praxis/handlers/json.rb
praxis-2.0.pre.36 lib/praxis/handlers/json.rb
praxis-2.0.pre.35 lib/praxis/handlers/json.rb
praxis-2.0.pre.34 lib/praxis/handlers/json.rb
praxis-2.0.pre.33 lib/praxis/handlers/json.rb
praxis-2.0.pre.32 lib/praxis/handlers/json.rb
praxis-2.0.pre.31 lib/praxis/handlers/json.rb
praxis-2.0.pre.30 lib/praxis/handlers/json.rb
praxis-2.0.pre.29 lib/praxis/handlers/json.rb
praxis-2.0.pre.28 lib/praxis/handlers/json.rb
praxis-2.0.pre.27 lib/praxis/handlers/json.rb
praxis-2.0.pre.26 lib/praxis/handlers/json.rb
praxis-2.0.pre.25 lib/praxis/handlers/json.rb