The good folks at LayerVault posted a easy way to add 'real-time' features on existing Ruby application without resorting to client side MCV or rewrite the entire app in Node.js, a while back. Their post show that you can update to all clients whenever your rails Models are updated [Reference 1] through delay_job & Active:Record Observer:
class FileObserver < ActiveRecord::Observer
observer :lv_file
def after_commit(record)
record.delay.report_updated
end
end
and
class LVFile < ActiveRecord::Base
def report_updated
Messenger.publish_message('file_updated', "file/#{self.id}")
end
end
[Reference 1] http://layervault.tumblr.com/post/31462727280/rails-in-realtime-part-2
Connect to socket.io server from client side javascript is easy. however I'm at lost how to implement Messenger.publish_message('file_updated', "file/#{self.id}") on rails server side. In the post they do mentioned that
The report_updated method makes a class method call to a separate Messenger class (our Socket.IO interface on the web app side) and reports that a file has changed to the appropriate room.
But I'm still not very sure how to implement Messager class in Rails so that Active:Record Observer will be able to connect to my socket.io server and send updates.
[PS] A conversation on HN indicates that they utilized this gem
The gem's wiki even included a brief demo:
require 'SocketIO'
client = SocketIO.connect("http://localhost", sync: true) do
before_start do
on_message {|message| puts message}
on_disconnect {puts "I GOT A DISCONNECT"}
end
after_start do
emit("loadLogs", "/var/www/rails_app/log/production.log")
end
end
puts "socket still running"
loop do
sleep 10
puts 'zzz'
end
The Messenger class doesn't have much to it. All you need is to create the connection, fire off the message and then wrap things up. This is the entirety of our messenger.rb:
require 'socketio-client'
class Messenger
def self.send_message!(name, args)
begin
SocketIO.connect(MESSENGER_SOCKETIO_ADDRESS, sync: true) do
after_start do
emit(name, args)
disconnect
end
end
rescue
end
end
end