开发者

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 开发者_JAVA技巧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!.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜