如何从Rails控制器推送到Faye Server?

sta*_*s25 1 ruby ruby-on-rails eventmachine faye

我有这个代码:

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
Run Code Online (Sandbox Code Playgroud)

我有客户订阅了Faye Server:

var subscription = client.subscribe('/foo', function (message) {
    getMessages();
});
Run Code Online (Sandbox Code Playgroud)

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

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')
}
Run Code Online (Sandbox Code Playgroud)

但是当我将此代码粘贴到我的create方法中时,它会使用EventMachine阻止rails线程,并且服务器不再起作用.

当我client.publish没有使用时EventMachine,我收到错误.

如何从服务器发布到Faye?我知道有宝石喜欢faye-railsprivate_pub,但我想知道如何自己做.有没有办法集成EventMachine和Rails?也许我应该在另一个线程上运行EventMachine?

小智 7

我没有使用Event Machine,但我在rails中使用Fay-web Socket,我使用瘦Web服务器为我的应用程序显示通知.

首先,将此行添加到 Gemfile中

gem 'faye'
gem 'thin' 
Run Code Online (Sandbox Code Playgroud)

现在!运行bundle install命令,用于安装gem及其依赖项.

创建一个faye.ru文件并添加给定的行(运行Faye服务器的一个rackup文件).

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

现在在application.erb文件中添加一行

<%= javascript_include_tag 'application', "http://localhost:9292/faye.js", 'data-turbolinks-track' => true %>
Run Code Online (Sandbox Code Playgroud)

创建一个名为broadcast的方法或任何适合您的名称websoket.rb(首先在其中创建websoket.rb文件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
Run Code Online (Sandbox Code Playgroud)

现在在您想要的模型或控制器中使用此方法.

在我的情况下,我在**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
Run Code Online (Sandbox Code Playgroud)

对于订户

<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>
Run Code Online (Sandbox Code Playgroud)

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

rackup faye.ru -s thin -E prodcution
Run Code Online (Sandbox Code Playgroud)

详情 Faye websocket