The application we’ll be working with is a simple chat application. If we enter a message in the text field at the bottom of the page and click “Send” the browser will send an AJAX request to save the message then update the browser to add the message to the main chat window.
incluse this in gem file
gem 'private_pub'
gem 'thin'
bundle install
-------------------------------------------
gem install faye
1) rails g model Message
class Message
include Mongoid::Document
include Mongoid::Timestamps
field :content, type: String
end
Am using Mongo DB
2) rails g controller messages
def index
@messages = Message.all
end
def create
@message = Message.create!(params[:message])
PrivatePub.publish_to("/messages/new", message: @message)
end
3) create 3 files in views/messages
index.html.erb
create.js.erb
_message.html.erb
------------------index.html.erb------------------------------
<h1>Chat</h1>
<ul id="chat">
<%= render @messages %>
</ul>
<%= form_for Message.new, remote: true do |f| %>
<%= f.text_field :content %>
<%= f.submit "Send" %>
<% end %>
<%= subscribe_to "/messages/new" %>
---------- create.js.erb --------------------------
<% publish_to "/messages/new" do %>
$("#chat").append("<%= j render(@message) %>");
$("#new_message")[0].reset();
<% end %>
------- _message.html.erb (partial ) --- dont forget its a partial
<li>
<span class="created_at"><%= message.created_at %></span>
<%= message.content %>
</li>
------------------------------------------------------------------------------------
rails g private_pub:install
-----------------------------------------------------------
$ rackup private_pub.ru -s thin -E productionU will get a error dont google ..simple
go to private_pub.ru
add this line and start now
Faye::WebSocket.load_adapter('thin')
$ rackup private_pub.ru -s thin -E production
fayee starts like this
roopesh@roopesh:~/Desktop/Reachmore$ rackup private_pub.ru -s thin -E production
>> Thin web server (v1.5.0 codename Knife)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:9292, CTRL+C to stop
-------------------------------------------------------------------------
go to app/assets/javascripts.application.js
//= require private_pub
-------------------------------------------------------
got to routesadd
resources :messages
------------------------------------------------------------------------------------
go to assets/javascripts/messages.js.coffee
paste this code as it is
PrivatePub.subscribe "/messages/new", (data, channel) -> alert data.message.content
Over
localhost:3000/messages
just send a message
open other browser
localhost:3000/messages
ull get a message