diff --git a/lib/protocol/websocket/coder.rb b/lib/protocol/websocket/coder.rb index 5d4a1a7..582ca1d 100644 --- a/lib/protocol/websocket/coder.rb +++ b/lib/protocol/websocket/coder.rb @@ -10,7 +10,7 @@ module WebSocket # @namespace module Coder # The default coder for WebSocket messages. - DEFAULT = JSON::DEFAULT + DEFAULT = JSON end end end diff --git a/lib/protocol/websocket/coder/json.rb b/lib/protocol/websocket/coder/json.rb index 7e6da6b..89ba7fa 100644 --- a/lib/protocol/websocket/coder/json.rb +++ b/lib/protocol/websocket/coder/json.rb @@ -9,25 +9,16 @@ module Protocol module WebSocket module Coder # A JSON coder that uses the standard JSON library. - class JSON - # Initialize a new JSON coder. - # @parameter options [Hash] Options to pass to the JSON library when parsing or generating. - def initialize(**options) - @options = options - end - + module JSON # Parse a JSON buffer into an object. - def parse(buffer) - ::JSON.parse(buffer, **@options) + def self.parse(buffer) + ::JSON.parse(buffer, symbolize_names: true) end # Generate a JSON buffer from an object. - def generate(object) - ::JSON.generate(object, **@options) + def self.generate(object) + ::JSON.generate(object) end - - # The default JSON coder. This coder will symbolize names. - DEFAULT = new(symbolize_names: true) end end end diff --git a/releases.md b/releases.md index 7ebaeda..6f246f8 100644 --- a/releases.md +++ b/releases.md @@ -1,5 +1,9 @@ # Releases +## Unreleased + + - Fix JSON 3 compatibility by applying `symbolize_names` only when parsing incoming messages. `Coder::JSON` is now a module with fixed parsing and generation behavior; pass a different coder to customize serialization. + ## v0.21.1 - If `Connection#close_write` fails, the connection will now be fully closed to prevent hanging connections. diff --git a/test/protocol/websocket/coder/json.rb b/test/protocol/websocket/coder/json.rb new file mode 100644 index 0000000..8106405 --- /dev/null +++ b/test/protocol/websocket/coder/json.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2026, by Samuel Williams. + +require "protocol/websocket/coder/json" + +describe Protocol::WebSocket::Coder::JSON do + let(:buffer) {'{"hello":"world"}'} + let(:object) {{hello: "world"}} + + it "parses object keys as symbols" do + expect(subject.parse(buffer)).to be == object + end + + it "generates JSON" do + expect(subject.generate(object)).to be == buffer + end +end