Skip to content

Instantly share code, notes, and snippets.

@olimart
Forked from bradgessler/active_exchange.rb
Created September 5, 2024 12:06
Show Gist options
  • Save olimart/d7e34b886f7c5bdeed065a8e7e8c5da4 to your computer and use it in GitHub Desktop.
Save olimart/d7e34b886f7c5bdeed065a8e7e8c5da4 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
ActiveCable.server.pubsub
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment