Skip to content

Commit

Permalink
Lazy initialize the protocol and adapter
Browse files Browse the repository at this point in the history
this ensures `Rage.cable.broadcast` is working correctly when called from a non-server process (e.g. Sidekiq)
  • Loading branch information
rsamoilov committed Jan 9, 2025
1 parent cd492f8 commit 0ccba00
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions lib/rage/cable/cable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@ module Rage::Cable
# run Rage.cable.application
# end
def self.application
@adapter = Rage.config.cable.adapter
# explicitly initialize the adapter
__adapter

protocol = Rage.config.cable.protocol
protocol.init(__router)

handler = __build_handler(protocol)
accept_response = [0, protocol.protocol_definition, []]
handler = __build_handler(__protocol)
accept_response = [0, __protocol.protocol_definition, []]

application = ->(env) do
if env["rack.upgrade?"] == :websocket
Expand All @@ -33,6 +31,15 @@ def self.__router
@__router ||= Router.new
end

# @private
def self.__protocol
@__protocol ||= Rage.config.cable.protocol.tap { |protocol| protocol.init(__router) }
end

def self.__adapter
@__adapter ||= Rage.config.cable.adapter
end

# @private
def self.__build_handler(protocol)
klass = Class.new do
Expand Down Expand Up @@ -96,11 +103,14 @@ def log_error(e)
#
# @param stream [String] the name of the stream
# @param data [Object] the object to send to the clients. This will later be encoded according to the protocol used.
# @return [true]
# @example
# Rage.cable.broadcast("chat", { message: "A new member has joined!" })
def self.broadcast(stream, data)
Rage.config.cable.protocol.broadcast(stream, data)
@adapter&.publish(stream, data)
__protocol.broadcast(stream, data)
__adapter&.publish(stream, data)

true
end

# @!parse [ruby]
Expand Down

0 comments on commit 0ccba00

Please sign in to comment.