Skip to content

Instantly share code, notes, and snippets.

@bradgessler
Last active September 12, 2024 19:26
Show Gist options
  • Save bradgessler/96e18648003e3232550cf10a907cb37c to your computer and use it in GitHub Desktop.
Save bradgessler/96e18648003e3232550cf10a907cb37c to your computer and use it in GitHub Desktop.
ActionExchange
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