Last active
September 12, 2024 19:26
-
-
Save bradgessler/96e18648003e3232550cf10a907cb37c to your computer and use it in GitHub Desktop.
ActionExchange
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ActiveExchange | |
class Channel | |
def initialize(name:, server: ActiveExchange.server) | |
@server = server | |
@channel = name | |
@queue = Queue.new | |
@subscribe = false | |
end | |
def broadcast(message) | |
Rails.logger.info "ActiveExchange: Publishing #{message.inspect} to #{@channel.inspect}" | |
@server.broadcast(@channel, message) | |
end | |
def subscribe | |
return if @subscribed | |
@subscribed = true | |
Rails.logger.info "ActiveExchange: Subscribed to #{@channel.inspect}" | |
@server.subscribe(@channel, -> (message) { @queue << message }) | |
end | |
def read | |
subscribe | |
@queue.pop | |
end | |
end | |
def self.server | |
ActionCable.server.pubsub | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment