如何从 Rails Controller 推送到 Faye Server?

How can I push to Faye Server from Rails Controller?

我有这个代码:

def create
    message = Message.new(text: params[:message][:text], author: params[:message][:author])
    if message.save
      render json: {result: 'success'}
    else
      render json: {result: 'failure'}
    end
  end

我有客户订阅了Faye Server:

var subscription = client.subscribe('/foo', function (message) {
    getMessages();
});

我想在创建消息时向 Faye 发布一些消息。正如 Faye Ruby 服务器文档中所列,我必须这样做:

require 'eventmachine'

EM.run {
  client = Faye::Client.new('http://localhost:9292/faye')

  client.subscribe('/foo') do |message|
    puts message.inspect
  end

  client.publish('/foo', 'text' => 'Hello world')
}

但是,当我将这段代码粘贴到我的 create 方法中时,它会阻塞带有 EventMachine 的 rails 线程,并且服务器不再工作。

当我在没有 EventMachine 的情况下使用 client.publish 时,出现错误。

如何从服务器发布到 Faye?我知道有像 faye-railsprivate_pub 这样的宝石,但我想自己弄清楚如何做。 EventMachine 和 Rails 有什么办法整合吗?也许我应该 运行 EventMachine 在不同的线程上?

我没有使用 Event Machine,但我在 rails 中使用了 Fay-web Socket,我正在使用 thin web-server 让我的应用程序显示通知。

首先你把这一行加入你 Gemfile

gem 'faye'
gem 'thin' 

Now ! run bundle install command for install gem and it's dependency.

Create a faye.ru file and add given line (a rackup file for run Faye server ).

require 'rubygems'
require 'thin'
require 'faye'
faye_server = Faye::RackAdapter.new(:mount => '/faye', :timeout => 45)
run faye_server

Now add line to your application.erb file

<%= javascript_include_tag 'application', "http://localhost:9292/faye.js", 'data-turbolinks-track' => true %>

Create a method with name broadcast or any name which is suitable for you in websoket.rb (first create websoket.rb file inside config/initializers ) .

module Websocket
  def broadcast(channel, msg)
    message = {:channel => channel, :data => msg}
    uri = URI.parse("http://localhost:9292/faye")
    Net::HTTP.post_form(uri, :message => message.to_json)
  end
end

Now use this method inside your model or controller where you want.

在我的例子中,我在 **Notification.rb 中使用它来发送通知。**

例子

after_create :send_notificaton 

def send_notification
    broadcast("/users/#{user.id}", {username: "#{user.full_name }", msg: "Hello you are invited for project--| #{project.name} | please check your mail"})
end

订阅者

<div id="websocket" style="background-color: #999999;">
</div>
<script>
$(function () {
var faye = new Faye.Client('http://localhost:9292/faye');
        faye.subscribe('/users/<%= current_user.id %>', function (data) {
            $('#websocket').text(data.username + ": " + data.msg);
        });
    });
</script>

现在! 运行 您的 faye.ru 文件使用终端

rackup faye.ru -s thin -E prodcution

详情 Faye websocket