nats-io / nats-pure.rb

Ruby client for NATS, the cloud native messaging system.
https://nats.io
Apache License 2.0
131 stars 30 forks source link

Fix lazy connection after code reload in Rails #124

Closed Envek closed 1 year ago

Envek commented 1 year ago

I tried to use lazily connected NATS client in a Rails app and got cryptic error undefined method '<<' for nil:NilClass from internals of the client (it tried to push a message to the pending queue which wasn't initialized yet).

It seems that somehow status was set to DISCONNECTED from unset state, but connection wasn't (re?)established

I suppose that it can be caused by Rails code reloading in developer environment, however can't be sure yet.

This is how I was trying to use the client:

# config/initializers/nats.rb
$nats = NATS::Client.new("nats://localhost:4222")

# app/controllers/test_controller.rb
class TestController < ApplicationController
  def publish
    $nats.publish('test', params.require(:message))
    redirect_back fallback_location: root_path
  end
end

NB: I couldn't make a reproduction test case for this, no idea how to test it outside real application.

This is follow-up for https://github.com/nats-io/nats-pure.rb/pull/116