Class: AceMQ::AMQP::JSONCodec

Inherits:
Object
  • Object
show all
Defined in:
lib/acemq/amqp/codec.rb

Overview

Reads and writes JSON.

The default, and the one format every AceMQ library has without an extra dependency, which is why an untyped message is assumed to be this one.

Keys go on the wire exactly as the payload spells them, because the wire name is the contract with the other four languages and a codec that quietly renamed total_cents to totalCents would be deciding that contract on the caller's behalf. Spell the keys the way the other services already read them.

Constant Summary collapse

CONTENT_TYPE =

What this codec writes, and what Java and .NET write.

"application/json"

Instance Method Summary collapse

Constructor Details

#initialize(symbolize_names: false) ⇒ JSONCodec

Returns a new instance of JSONCodec.

Parameters:

  • symbolize_names (Boolean) (defaults to: false) —

    whether decoded objects come back with symbol keys. False by default: a key that came off the wire is data, and turning arbitrary remote data into symbols is a decision worth making on purpose.



112
113
114
115
# File 'lib/acemq/amqp/codec.rb', line 112

def initialize(symbolize_names: false)
  @symbolize_names = symbolize_names
  freeze
end

Instance Method Details

#can_decode?(content_type) ⇒ Boolean

Accepts application/json, text/json, any +...+json+ media type, and a message whose sender set no content type at all.

The last of those is the difference between this codec and the YAML and TOML codecs in the other libraries: JSON is the default format, so an untyped message is far more likely to be JSON than anything else, and something has to be willing to read it.

Returns:

  • (Boolean)


142
143
144
145
146
147
148
# File 'lib/acemq/amqp/codec.rb', line 142

def can_decode?(content_type)
  lower = content_type.to_s.downcase
  return true if lower.empty?

  lower.start_with?(CONTENT_TYPE) || lower.start_with?("text/json") ||
    lower.include?("+json")
end

#content_type ⇒ Object



117
# File 'lib/acemq/amqp/codec.rb', line 117

def content_type = CONTENT_TYPE

#decode(body) ⇒ Object

Parameters:

  • body (String)

Returns:

  • (Object)


129
130
131
132
133
# File 'lib/acemq/amqp/codec.rb', line 129

def decode(body)
  JSON.parse(body.to_s, symbolize_names: @symbolize_names)
rescue JSON::ParserError => e
  raise DecodeError, "this message is not JSON: #{e.message}"
end

#encode(payload) ⇒ String

Parameters:

  • payload (Object)

Returns:

  • (String)


121
122
123
124
125
# File 'lib/acemq/amqp/codec.rb', line 121

def encode(payload)
  JSON.generate(payload)
rescue JSON::GeneratorError, NoMethodError => e
  raise EncodeError, "this payload will not serialise as JSON: #{e.message}"
end