Module: Turbocable::Codecs::JSON

Defined in:
lib/turbocable/codecs/json.rb

Overview

JSON codec — the default serialization format.

Encodes payload hashes (and other JSON-serializable values) to a UTF-8 JSON string. The encoding is compatible with the actioncable-v1-json WebSocket sub-protocol that turbocable-server supports.

The server does not enforce a content-type header in the NATS payload; it tries JSON first then MessagePack. The .content_type value here is informational only and matches the WebSocket sub-protocol name so that routing and test assertions can reference a stable constant.

Class Method Summary collapse

Class Method Details

.content_typeString

Returns the WebSocket sub-protocol name for this codec.

Returns:

  • (String)

    the WebSocket sub-protocol name for this codec



19
20
21
# File 'lib/turbocable/codecs/json.rb', line 19

def self.content_type
  "actioncable-v1-json"
end

.decode(bytes) ⇒ Object

Deserializes a JSON string back to a Ruby value. Intended for testing and round-trip specs; production subscribers are WebSocket clients, not this gem.

Parameters:

  • bytes (String)

    JSON-encoded bytes

Returns:

  • (Object)


59
60
61
# File 'lib/turbocable/codecs/json.rb', line 59

def self.decode(bytes)
  ::JSON.parse(bytes, symbolize_names: false)
end

.encode(payload) ⇒ String

Serializes payload to a JSON string (encoded as UTF-8 bytes).

Parameters:

  • payload (Object)

    any JSON-serializable value (Hash, Array, etc.)

Returns:

  • (String)

    UTF-8-encoded JSON bytes

Raises:



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/turbocable/codecs/json.rb', line 35

def self.encode(payload)
  unless PRIMITIVE_TYPES.any? { |t| payload.is_a?(t) }
    raise Turbocable::SerializationError.new(
      "JSON codec cannot encode #{payload.class}: not a JSON-serializable type. " \
      "Use a Hash, Array, String, Numeric, Boolean, or nil.",
      codec_name: :json,
      payload_class: payload.class
    )
  end
  ::JSON.generate(payload)
rescue ::JSON::GeneratorError, ::TypeError => e
  raise Turbocable::SerializationError.new(
    "JSON codec failed to encode #{payload.class}: #{e.message}",
    codec_name: :json,
    payload_class: payload.class
  )
end