-
-
Save as181920/5cd83b5d9157cc644d672b9176427958 to your computer and use it in GitHub Desktop.
PostgreSQL LISTEN/NOTIFY example for ruby
This file contains hidden or 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
# | |
# A: | |
# pubsub = PgPubSub.new('channelname') | |
# pubsub.subscribe do |data| | |
# puts "data: #{data} is coming!" | |
# end | |
# | |
# B: | |
# pubsub = PgPubSub.new('channelname') | |
# pubsub.publish("hello world") | |
# | |
# becomes | |
# A: | |
# => data: hello world is coming! | |
# | |
# | |
# "C" before channel name is not required. | |
# But when channel name starts with digit, e.g. LISTEN 1NAME | |
# it causes syntax error. So, it fix erorr. | |
# | |
class PgPubSub | |
def initialize(channel) | |
@channel = channel | |
end | |
def subscribe | |
connection.execute "LISTEN C#{@channel}" | |
loop do | |
connection.raw_connection.wait_for_notify do |event, id, data| | |
yield data | |
end | |
end | |
ensure | |
connection.execute "UNLISTEN C#{@channel}" | |
end | |
def publish(json) | |
connection.execute "NOTIFY C#{@channel}, #{connection.quote json}" | |
end | |
private | |
def connection | |
ActiveRecord::Base.connection | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment