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
-
.content_type ⇒ String
The WebSocket sub-protocol name for this codec.
-
.decode(bytes) ⇒ Object
Deserializes a JSON string back to a Ruby value.
-
.encode(payload) ⇒ String
Serializes
payloadto a JSON string (encoded as UTF-8 bytes).
Class Method Details
.content_type ⇒ String
Returns 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.
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).
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.}", codec_name: :json, payload_class: payload.class ) end |