socketry / async-websocket

Asynchronous WebSocket client and server, supporting HTTP/1 and HTTP/2 for Ruby.
MIT License
166 stars 18 forks source link

`connection.write` with not string argument raises `TypeError` #68

Closed ksimmi closed 2 months ago

ksimmi commented 2 months ago

Hello!

I tried to explore gem with an example and it not working for me. The example contains lines:

...
connection.write({user: USER, text: line})
...
connection.write({
  user: USER,
  status: "connected",
})
...

But I get an error when I call connection.write with Hash argument. I patched Async::WebSocket::Connection#write with breakpoint to debug.

class Async::WebSocket::Connection # < ::Protocol::WebSocket::Connection
  def write(message, **options)
    # This is a compatibility shim for the previous implementation. We may want to eventually deprecate this use case... or maybe it's convenient enough to leave it around.
    if message.is_a?(String)
      if message.encoding == Encoding::UTF_8
        return send_text(message, **options)
      else
        return send_binary(message, **options)
      end
    end

    binding.pry # breakpoint

    message.send(self, **options)
  end
end

My console output:

=> 24:   binding.pry
    25:   message.send(self, **options)

)> message
=> {:user=>"anonymous", :status=>"connected"}

)> self
=> #<Async::WebSocket::Connection:0x00007ff90702ed30

message.send expects symbol or string: TypeError: #<Async::WebSocket::Connection:0x00007f493bd4eb18 ... is not a symbol nor a string

If I call connection.write with string argument like connection.write({user: USER, text: line}.to_json) it will work. But I don't like this solution because the comment from code above. # This is a compatibility shim for the previous implementation. We may want to eventually deprecate this use case... or maybe it's convenient enough to leave it around.

Ruby 3.2.2

ioquatix commented 2 months ago

Apologies, the example was not updated with a change in the interface, let me fix it.

ioquatix commented 2 months ago

The examples are updated and they all work now.

In short, previously write would accept rich values and convert them to JSON, but this was too opinionated. So, we extracted that functionality out. It was pretty convenient, so I might consider how to re-add it in the future.

ksimmi commented 2 months ago

In first time I catched NoMethodError: undefined method `generate' for Protocol::WebSocket::TextMessage:Class (NoMethodError)

I fixed it by bundle update.

Thank you.