简体   繁体   中英

Listening to Juggernaut events from Rails

I'm building a simple real time chat using Juggernaut, Redis, SQLite and Rails 3.1

I want to write a new message to every user when another has been disconnected (for instance he closed the window), this is to listen to the Juggernaut's client disconnected event.

Juggernaut docs says I can do this in the server side (Ruby)

Juggernaut.subscribe do |event, data|
  # Use event/data
end

Problem is that I don't know where I should put this code inside my Rails app (controller, model, observer?). I've tried to placed it into the model, however the server doesn't response to any request with that chunk of code into the model.

I think I should listen to that event from the server side because if the user was disconnected because he closed the window then I don't have a "client side" for that user.

Probably I'm missing something about how Juggernaut works. Any help will be appreciated.

Ok, finally I'm answering myself:

I've found problem is that when the process running calls Juggernaut.subscribe it freezes until a Juggernaut event is triggered. Therefore you can't call Juggernaut from the server process, you need a new process to run that code.

My code now looks like this: Model:

class MyModel < ActiveRecord::Base

  class << self
    def subscribe
      Juggernaut.subscribe do |event, data|
        case event
          when :subscribe
            # do something
          when :unsubscribe
            # do something else
        end
      end
    end
  end

end

And then I have a ruby script myapp/scripts/juggernaut_listener:

#!/usr/bin/env ruby
require File.expand_path('../../config/environment',  __FILE__)

puts "Starting juggernaut listener"
MyModel.subscribe

So after lunching the server I need to lunch the Juggernaut listener like this:

./script/participations_listener

(Note you should give +x to the script).

Hope it's helpful to someone!.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM