简体   繁体   English

聆听Rails的剑圣事件

[英]Listening to Juggernaut events from Rails

I'm building a simple real time chat using Juggernaut, Redis, SQLite and Rails 3.1 我正在使用Juggernaut,Redis,SQLite和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) 剑圣文档说我可以在服务器端做到这一点(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?). 问题是我不知道将这段代码放在Rails应用程序的哪个位置(控制器,模型,观察者?)。 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. 我发现问题在于,当运行的进程调用Juggernaut.subscribe时,它会冻结,直到触发Juggernaut事件为止。 Therefore you can't call Juggernaut from the server process, you need a new process to run that code. 因此,您无法从服务器进程中调用Juggernaut,您需要一个新进程来运行该代码。

My code now looks like this: Model: 我的代码现在看起来像这样: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: 然后我有一个ruby脚本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). (注意,您应该给脚本加上+ x)。

Hope it's helpful to someone!. 希望对某人有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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