From 36afd8a7192e18aa6cf4ccde06248f7dd6e39ade Mon Sep 17 00:00:00 2001 From: Nicolas ZERMATI Date: Wed, 2 Sep 2015 14:16:07 +0200 Subject: [PATCH] Add redisse hooks --- README.md | 3 +++ lib/redisse/configuration.rb | 44 ++++++++++++++++++++++++++++++++++++ lib/redisse/server.rb | 2 ++ 3 files changed, 49 insertions(+) diff --git a/README.md b/README.md index 313d7e1..b4686c0 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,9 @@ application, and serving them to your clients. keep in mind that a client will receive events of all types from their channels. To handle access rights, use channels instead. +* **Hooks** in order to do custom actions during the (dis)connection of the + clients to the server. + ## Rationale Redisse’s design comes from these requirements: diff --git a/lib/redisse/configuration.rb b/lib/redisse/configuration.rb index 89106d2..0338e53 100644 --- a/lib/redisse/configuration.rb +++ b/lib/redisse/configuration.rb @@ -39,6 +39,50 @@ def self.channels(*, &block) end end + # Public: Define a custom piece of code to run during a new connection. + # + # Calls the given block with a Rack environment. + # + # block - The block we want to run at client connection + # + # Examples + # + # Redisse.on_connect do |env| + # puts "A new client just connected to Redisse" + # end + # + # Redisse.on_connect({}) + # # => "A new client just connected to Redisse" + def self.on_connect(env, &block) + if block + @on_connect = block + elsif @on_connect + @on_connect.call(env) + end + end + + # Public: Define a custom piece of code to run during a disconnection. + # + # Calls the given block with a Rack environment. + # + # block - The block we want to run at client disconnection + # + # Examples + # + # Redisse.on_disconnect do |env| + # puts "A new client just disconnected from Redisse" + # end + # + # Redisse.on_disconnect({}) + # # => "A new client just disconnected from Redisse" + def self.on_disconnect(env, &block) + if block + @on_disconnect = block + elsif @on_disconnect + @on_disconnect.call(env) + end + end + self.redis_server = ENV['REDISSE_REDIS'] || 'redis://localhost:6379/' self.default_port = ENV['REDISSE_PORT'] || diff --git a/lib/redisse/server.rb b/lib/redisse/server.rb index 5d9f7c9..6d71bc0 100644 --- a/lib/redisse/server.rb +++ b/lib/redisse/server.rb @@ -70,6 +70,7 @@ def response(env) channels = Array(redisse.channels(env)) return not_found if channels.empty? subscribe(env, channels) or return service_unavailable + redisse.on_connect(env) history_events(env, channels) heartbeat(env) streaming_response(200, { @@ -80,6 +81,7 @@ def response(env) end def on_close(env) + redisse.on_disconnect(env) unsubscribe(env) stop_heartbeat(env) end