Class: Ears::Middlewares::JSON

Inherits:
Ears::Middleware show all
Defined in:
lib/ears/middlewares/json.rb

Overview

A middleware that automatically parses your JSON payload.

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ JSON

Returns a new instance of JSON.

Parameters:

  • opts (Hash) (defaults to: {})

    The options for the middleware.

Options Hash (opts):

  • :on_error (Proc) — default: Proc.new { :reject }

    A Proc to be called when an error occurs during processing.

  • :symbolize_keys (Boolean) — default: true

    Whether to symbolize the keys of your payload.



11
12
13
14
15
# File 'lib/ears/middlewares/json.rb', line 11

def initialize(opts = {})
  super()
  @on_error = opts.fetch(:on_error, Proc.new { :reject })
  @symbolize_keys = opts.fetch(:symbolize_keys, true)
end

Instance Method Details

#call(delivery_info, metadata, payload, app) ⇒ Object



17
18
19
20
21
22
23
24
25
26
# File 'lib/ears/middlewares/json.rb', line 17

def call(delivery_info, , payload, app)
  begin
    parsed_payload =
      MultiJson.load(payload, symbolize_keys: symbolize_keys)
  rescue => e
    return on_error.call(e)
  end

  app.call(delivery_info, , parsed_payload)
end