I have searched a lot but didn't get any solution. I am using rails 3.2.16 and ruby 1.9.3. There is a railscast for Messaging with faye which was very helpful. And I have found one more solution which is this:
The difference between both is that the railscast solution sends AJAX request each time while saving the chat in database which I have done using the other solution without sending any AJAX request. But this would be like public chat.
I am not getting that without AJAX requests in the second solution how can I create private chats, group chats and all. How can I make a channel and pass it. As a plain javascript file serves the publishing code.
Here is my code which I have modified a bit:
index.html.erb
<ul id="chat">
<% @chat_messages.each do |chat_message| %>
<li>
<%= chat_message.created_at.strftime('%-d/%-m/%Y %k:%M:%S') %>
<%= ':' %>
<%= chat_message.message %>
</li>
<% end %>
</ul>
<hr/>
<form>
<input id="message" name="message" type="text"></input>
<input id="submit" type="submit" value="Post"></input>
</form>
<hr/>
realtime_chat_controller.rb
class RealtimeChatController < FayeRails::Controller
channel '/chat' do
subscribe do
Conversation.create(message: message['message'])
end
end
end
conversations_controller.rb
class ConversationsController < ApplicationController
def index
@chat_messages = Conversation.all
end
end
conversation.rb
class Conversation < ActiveRecord::Base
attr_accessible :message
HISTORY = 20
# def initialize(options = {})
# options.each_pair do |n, v|
# public_send("#{n}=", v)
# end
# self.created_at ||= Time.now
# end
def push
self.class.push self
self
end
def self.push(chat_message)
@chat_messages ||= []
@chat_messages << chat_message
@chat_messages.shift if @chat_messages.size > HISTORY
end
# def self.create(options)
# new(options).tap { |cm| push cm }
# end
def self.recent
@chat_messages ||= []
end
end
js file
var client;
client = new Faye.Client('/faye');
client.subscribe('/chat', function(payload) {
var time;
time = moment(payload.created_at).format('D/M/YYYY H:mm:ss');
return $('#chat').append("<li>" + time + " : " + payload.message + "</li>");
});
$(document).ready(function() {
var button, input;
input = $('#message');
button = $('#submit');
return $('form').submit(function(event) {
var publication;
button.attr('disabled', 'disabled');
button.val('Posting...');
publication = client.publish('/chat', {
message: input.val(),
created_at: new Date()
});
publication.callback(function() {
input.val('');
button.removeAttr('disabled');
return button.val("Post");
});
publication.errback(function() {
button.removeAttr('disabled');
return button.val("Try Again");
});
event.preventDefault();
return false;
});
});
window.client = client;
application.rb
config.middleware.delete Rack::Lock
config.middleware.use FayeRails::Middleware, mount: '/faye', :timeout => 25 do
map '/chat' => RealtimeChatController
map default: :block
end
Aucun commentaire:
Enregistrer un commentaire