Sha256: fb16a06b9a81d95fe53eb223b552f63f4b7781fbd45d55fc4a329c52c6ebc5d3

Contents?: true

Size: 1014 Bytes

Versions: 13

Compression:

Stored size: 1014 Bytes

Contents

require 'ears/middleware'
require 'multi_json'

module Ears
  module Middlewares
    # A middleware that automatically parses your JSON payload.
    class JSON < Middleware
      # @param [Hash] opts The options for the middleware.
      # @option opts [Proc] :on_error (Proc.new { :reject }) A Proc to be called when an error occurs during processing.
      # @option opts [Boolean] :symbolize_keys (true) Whether to symbolize the keys of your payload.
      def initialize(opts = {})
        super()
        @on_error = opts.fetch(:on_error, Proc.new { :reject })
        @symbolize_keys = opts.fetch(:symbolize_keys, true)
      end

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

        app.call(delivery_info, metadata, parsed_payload)
      end

      private

      attr_reader :symbolize_keys, :on_error
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
ears-0.14.1 lib/ears/middlewares/json.rb
ears-0.14.0 lib/ears/middlewares/json.rb
ears-0.13.0 lib/ears/middlewares/json.rb
ears-0.12.0 lib/ears/middlewares/json.rb
ears-0.11.2 lib/ears/middlewares/json.rb
ears-0.11.1 lib/ears/middlewares/json.rb
ears-0.11.0 lib/ears/middlewares/json.rb
ears-0.10.1 lib/ears/middlewares/json.rb
ears-0.10.0 lib/ears/middlewares/json.rb
ears-0.9.3 lib/ears/middlewares/json.rb
ears-0.9.2 lib/ears/middlewares/json.rb
ears-0.9.0 lib/ears/middlewares/json.rb
ears-0.8.2 lib/ears/middlewares/json.rb