Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

ruby - How can I push to Faye Server from Rails Controller?

I have this code:

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

I have client subscribed to Faye Server:

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

I want to publish some message to Faye when a message is created. As listed in Faye Ruby Sever documentation, I have to do like this:

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')
}

But when I paste this code into my create method, it blocks the rails thread with EventMachine and server doesn't work any more.

When I use client.publish without EventMachine, I get an error.

How can I publish to Faye from server? I know that there are gems like faye-rails or private_pub, but I want to figure out how to do it myself. Is there any way to integrate EventMachine and Rails? Maybe I should run EventMachine on a different thread?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I did't use Event Machine but I use Fay-web Socket in rails , I am using thin web-server for my application to show notification.

First you add this line into you 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.

In my case I am using this inside the **Notification.rb to sending notification.**

Example

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

For subscriber

<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>

Now ! Run your faye.ru file using terminal

rackup faye.ru -s thin -E prodcution

For details Faye websocket


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...