Skip to content

Commit 667b042

Browse files
Fix JSON 3 message generation. (#27)
1 parent b041f11 commit 667b042

4 files changed

Lines changed: 29 additions & 15 deletions

File tree

‎lib/protocol/websocket/coder.rb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ module WebSocket
1010
# @namespace
1111
module Coder
1212
# The default coder for WebSocket messages.
13-
DEFAULT = JSON::DEFAULT
13+
DEFAULT = JSON
1414
end
1515
end
1616
end

‎lib/protocol/websocket/coder/json.rb‎

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,25 +9,16 @@ module Protocol
99
module WebSocket
1010
module Coder
1111
# A JSON coder that uses the standard JSON library.
12-
class JSON
13-
# Initialize a new JSON coder.
14-
# @parameter options [Hash] Options to pass to the JSON library when parsing or generating.
15-
def initialize(**options)
16-
@options = options
17-
end
18-
12+
module JSON
1913
# Parse a JSON buffer into an object.
20-
def parse(buffer)
21-
::JSON.parse(buffer, **@options)
14+
def self.parse(buffer)
15+
::JSON.parse(buffer, symbolize_names: true)
2216
end
2317

2418
# Generate a JSON buffer from an object.
25-
def generate(object)
26-
::JSON.generate(object, **@options)
19+
def self.generate(object)
20+
::JSON.generate(object)
2721
end
28-
29-
# The default JSON coder. This coder will symbolize names.
30-
DEFAULT = new(symbolize_names: true)
3122
end
3223
end
3324
end

‎releases.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Releases
22

3+
## Unreleased
4+
5+
- 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.
6+
37
## v0.21.1
48

59
- If `Connection#close_write` fails, the connection will now be fully closed to prevent hanging connections.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# frozen_string_literal: true
2+
3+
# Released under the MIT License.
4+
# Copyright, 2026, by Samuel Williams.
5+
6+
require "protocol/websocket/coder/json"
7+
8+
describe Protocol::WebSocket::Coder::JSON do
9+
let(:buffer) {'{"hello":"world"}'}
10+
let(:object) {{hello: "world"}}
11+
12+
it "parses object keys as symbols" do
13+
expect(subject.parse(buffer)).to be == object
14+
end
15+
16+
it "generates JSON" do
17+
expect(subject.generate(object)).to be == buffer
18+
end
19+
end

0 commit comments

Comments
 (0)