Skip to content

Instantly share code, notes, and snippets.

@seufagner
Last active August 29, 2015 13:56
Show Gist options
  • Save seufagner/8830356 to your computer and use it in GitHub Desktop.
Save seufagner/8830356 to your computer and use it in GitHub Desktop.
Pusher wrapper - use server and client gems
module Realtime
class PusherWrapper
attr_reader :socket
def initialize
Pusher.app_id = '<<app ID>>'
Pusher.key = '<<app key>>'
Pusher.secret = '<<secret key>>'
@socket = PusherClient::Socket.new("<<app key>>")
async = true
@socket.connect(async)
end
def subscribe(channel_name, event_name, &callback)
raise InvalidChannelName, "channel name cannot be blank" if channel_name.blank?
raise InvalidEventName, "event name cannot be blank" if event_name.blank?
raise InvalidCallback, "callback cannot be nil" unless block_given?
@socket.subscribe(channel_name)
@socket[channel_name].bind(event_name) do |data|
callback.call(data)
end
end
def send_to(channel_name, event_name)
@channel_name = channel_name
@event_name = event_name
self
end
def message(json_message)
raise InvalidChannelName, "channel name cannot be blank" if channel_name.blank?
raise InvalidEventName, "event name cannot be blank" if event_name.blank?
EM.run {
deferrable = Pusher[@channel_name].trigger_async(@event_name, json_message)
}
# deferrable.callback { # called on success
# puts "Message sent successfully."
# EM.stop
# }
# deferrable.errback { |error| # called on error
# puts "Message could not be sent."
# puts error
# EM.stop
# }
end
class InvalidChannelName < StandardError; end
class InvalidEventName < StandardError; end
class InvalidCallback < StandardError; end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment