module SnipSnap::JSONBodyExtension

# SnipSnap::JSONBodyExtension

Require Path: `snipsnap/extensions/json_body`

Public Class Methods

registered(app) click to toggle source
# File lib/snipsnap/extensions/json_body.rb, line 6
def self.registered(app)
  app.before do
    # If there's a body, assume it is JSON and try to parse it.

    body = ''

    begin
      body = request.env["rack.input"].read
      @body = body
      request.env["rack.input"].rewind
    rescue => e
      logger.debug "ERROR reading rack.input: #{e.inspect}"
    end

    @json = nil

    # XXX Check for application/json content type?
    if body.index("{") or body.index("[")
      begin
        @json = JSON.parse(body)
        puts "JSON: "
        puts JSON.pretty_generate(@json)
      rescue
        logger.info "ERROR: Could not parse body as JSON"
      end
    end
  end
end