Push data from rails app to clients - ruby-on-rails

I'm working on a rails app that will primarily be exposed by an api to various mobile clients (iOS, android etc). The application involves users submitting data to the server (via api calls), but what I want to include is the ability to push this data down to other clients. The general concept is similar to a messaging app, where I submit a message to the server from me client and the receiver is pushed the message from the server.
The only method I know of at the moment is to constantly poll the server, but there must be better tech solutions than this. Any ideas?

I would look at using a websocket within the page to push the updates.
You could implement this using Faye, which falls back to long polling and other work-arounds for browsers without websocket support. Faye has a pure-ruby implementation, so you could probably work out access to your model layer.
Edit:
Also, this is a project that combines Faye with Rails. It is fairly new, but might do what you want. Faye-Rails

You should check out http://www.pusher.com
Pusher is a hosted API for quickly, easily and securely adding scalable realtime functionality to web and mobile apps.
If you need self-hosted solution, then you should check out slanger gem https://github.com/stevegraham/slanger which is server implementation for pusher client libraries. When you feel you need hosted solution, you just change URL's.
Slanger is an open source server implementation of the Pusher protocol written in Ruby. It is designed to scale horizontally across N nodes and to be agnostic as to which Slanger node a subscriber is connected to, i.e subscribers to the same channel are NOT required to be connected to the same Slanger node. Multiple Slanger nodes can sit behind a load balancer with no special configuration. In essence it was designed to be very easy to scale.

Ruby has it's own event-processing library, implemented like a gem:
https://github.com/eventmachine/eventmachine
Maybe it helps you

I prefer event machine over any other solution. It is somewhat more complicated that faye but you can write way more sophisticated code using event machine.
You might wanna check this peepcode screencast on event machine

Related

NodeJS as an instant messaging server for a MVP chat service

I am working on a chat service with some unique features in it, and thinking about a server to dispatch messages and do all the IM-related stuff. First-priority client is going to be for iOS, built with Swift.
Is it feasible to create server, based on NodeJS Express, or may be Loopback? I have had a look at multiple choices, including ready solutions, like QuickBlox, Parse.
As for creating it from scratch, I think about NodeJS or Erlang.
At what stage should I make a decision so that not to waste too much time on reconfiguring everything for scaling and rapidity and convenience of development?
With technologies like Socket.io, Node.js, and Express, you could make a chat application fairly quickly.
Sockets are typically the best solution and the most common route to implementing a chat system, as they provide two way communication between the client and the server.
You could use practically any backend for a socket server, but it may end up being quicker to use Node.js and socket.io depending on your comfortability level with JavaScript.
All you would need is a socket compatible server and a client side library that connects to a socket server - there are plenty of JavaScript libs out there, including a socket.io-client.
Check out socket.io's chat demo on their site for a quick look at how it works:
http://socket.io/demos/chat/
They even provide a first party iOS Swift client:
https://github.com/socketio/socket.io-client-swift
Personally I recommend you to checkout SailsJS, a great framework for building API & chat server at the same time. It adopts socket.io internally so every route in a Sails app is compatible with socket.io (in other words, you can decide to call an API request via Socket anytime you wish!)
I've built a complete, working iOS App having chat feature. Its backend was completely developed using SailsJS. It saved me hundreds of hours. Sails documentation also mentions about scaling for production. Please have a look at http://sailsjs.org

Rails - how to have the client receive/process messages from the server without AJAX?

This may be sort of a newb-ish question. I know you can do this kind of thing in Node.js pretty easily, but I don't know what it's called and haven't had much luck with Google.
Basically, I am trying to build a simple tic-tac-toe server with Ruby on Rails. Players connect to each other, and moves are recorded and results processed live. If it was just having the user send messages to the server, that would be easily done with AJAX. However, I want to have the client wait and listen for the server to point out that the other player has made a move, and then automatically respond to that. I could do this by pinging the server with AJAX constantly, but there must be a better way. I feel like I'm missing some big technology that I haven't found yet just because I'm not entirely sure how to describe it or what it would be called.
Would I want to have the client connect directly to the server and maintain a live connection? If so, how would I do that? If not, what is the better way to do this? How do online games and stock tickers and streaming services provide their content to the client, and what tools does Rails give me to do something similar?
Check eventmachine in ruby
some links
https://github.com/eventmachine/eventmachine/wiki
http://20bits.com/article/an-eventmachine-tutorial
http://rubysource.com/introduction-to-event-machine
There is a faye and private_pub gem which makes things simpler .
There are railcasts available.
http://railscasts.com/episodes/260-messaging-with-faye
http://railscasts.com/episodes/316-private-pub
I recommend trying private_pub which is built on top on faye which uses eventmachine which can solve most of your questions
the pub/sub model helps to the client to subscribe to its channel
, so you can push updated to the channel which will be eventually passed to the client.
Your question and my answers
Q. Would I want to have the client connect directly to the server and maintain a live connection? If so, how would I do that?
A. You can use private_pub or faye to establish long connections and push data
also Check our later for pusher.com they provide services on commercial basis.
Q.How do online games and stock tickers and streaming services provide their content to the client, and what tools does Rails give me to do something similar?
A. AFAIK everyone uses some sort of push technology. pub/sub model. ruby has some gems available for such requirements, faye private_pub some of them..
For a commercial solution, check out Pusher, it does pretty much exactly what you want:
http://pusher.com/
For open source solutions, check out Faye (a pub/sub messaging server):
http://faye.jcoglan.com/
and some awesome railscasts explaining it:
http://railscasts.com/episodes/260-messaging-with-faye
http://railscasts.com/episodes/316-private-pub

What WebSockets system should I use for this?

I'm building a Rails app where I need a real time commenting system. I'm going to use WebSockets, but I'm new to them and I'm kinda lost. I tried em-websockets and websocket-rails, but neither worked well with what I have to do. I also though of a Node.JS and Socket.io app, but I don't know how to start with that.
What I want to do is send a WebSocket message when a new comment is made on a post, on the create action of my CommentsController. I'll send a message containing the comment content and creator and the post ID.
Thanks in advance! :D
Sorry, but I dont think so. Be careful with WebSockets. It is fundamental concept that provides a very powerful mechanism.
Websockets is good for super, absolutely real-time applications like online games. For commenting system (even realtime) you dont need them, the AJAX is more then enought for this.
You could use a realtime hosted service if you don't want to deal with your own realtime infrastructure, fallbacks for older browsers, scaling complications etc.
I recently wrote a post on Smashing Mag on building a realtime commenting system. It uses PHP and Pusher (who I work for) but the separation between client and server should meant that you could use any backend technology/service. It also demonstrates how to progressively enhance your app.
The most commonly used self-hosted ruby technologies for realtime communication does seem to be Faye, as #Alfred suggested.
Just using websockets as the only available transport is not a good idea, because websockets are not yet supported in every browser. Luckily for example Faye does support multiple transports so that it will work in every browser. I also found this interesting video in the past explaining how you could use Faye in conjunction with RoR from RailsCast.

WebSockets and Heroku: pushing data to the user

I am build a real time web application using Ruby on Rails and Heroku seems to be the best option for hosting it.
I would prefer pushing new data to the user, when it becomes available, instead of pulling it by sending AJAX requests every few seconds.
Pusher seems to be suggested by Heroku for a such kind of job, but it has some limitations, brings additional costs, and makes you dependent on an external API.
Is there any other option to use WebSockets on Heroku?
If you wanna do websockets you need to use a different server besides rails. And since your on heroku you don't have the flexibility.
Optionally you can host a websockets enabled node server on an ec2 micro instance. Then in your rails app when you want to push -- do a request to the node server and the it will go to the clients.
If you only need one way communication try using Server Side events.
There are two options that you can use with Heroku aside from Pusher:
1) Like Eric Fode mentioned above, you could use SSE given you don't need two-way communication. There is a Heroku add-on which you could leverage for this: https://addons.heroku.com/eshq
2) There is another lesser known library called Faye which you could look into. It supports both Node.js and Ruby servers and it's based on the Bayeux Protocol
Heroku now has support for WebSockets: https://devcenter.heroku.com/articles/heroku-labs-websockets
While WebSockets isn't currently supported, apparently you can use Socket.io on Heroku, configuring it for long-polling.

How can I retrieve updated records in real-time? (push notifications?)

I'm trying to create a ruby on rails ecommerce application, where potential customers will be able to place an order and the store owner will be able to receive the order in real-time.
The finalized order will be recorded into the database (at the moment SQLite), and the storeowner will have a browser window open, where the new orders will appear just after the order is finalized.
(Application info: I'm using the HOBO rails framework, and planning to host the app in Heroku)
I'm now considering the best technology to implement this, as the application is expected to have a lot of users sending in a lot of orders:
1) Each browser window refreshes the page every X minutes, polling the server continuously for new records (new orders). Of course, this puts a heavy load on the server.
2) As above, but poll the server with some kind of AJAX framework.
3) Use some kind of server push technology, like 'comet' asynchronous messaging. Found Juggernaut, only problem is that it is using Flash and custom ports, and this could be a problem as my app should be accessible behind corporate firewalls and NAT.
4) I'm also checking node.js framework, seems to be efficient for this kind of asynchronous messaging, though it is not supported in Heroku.
Which is the most efficient way to implement this kind of functionality? Is there perhaps another method that I have not thought of?
Thank you for your time and help!
Node.js would probably be a nice fit - it's fast, loves realtime and has great comet support. Only downside is that you are introducing another technology into your solution. It's pretty fun to program in tho and a lot of the libraries have been inspired by rails and sinatra.
I know heroku has been running a node.js beta for a while and people were using it as part of the recent nodeknockout competition. See this blog post. If that's not an option, you could definitely host it elsewhere. If you host it at heroku, you might be able to proxy requests. Otherwise, you could happily run it off a sub domain so you can share cookies.
Also checkout socket.io. It does a great job of choosing the best way to do comet based on the browser's capabilities.
To share data between node and rails, you could share cookies and then store the session data in your database where both applications can get to it. A more involved architecture might involve using Redis to publish messages between them. Or you might be able to get away with passing everything you need in the http requests.
In HTTP, requests can only come from the client. Thus the best options are what you already mentioned (polling and HTTP streaming).
Polling is the easier to implement option; it will use quite a bit of bandwidth though. That's why you should keep the requests and responses as small as possible, so you should definitely use XHR (Ajax) for this.
Your other option is HTTP streaming (Comet); it will require more work on the set up, but you might find it worth the effort. You can give Realtime on Rails a shot. For more information and tips on how to reduce bandwidth usage, see:
http://ajaxpatterns.org/Periodic_Refresh
http://ajaxpatterns.org/HTTP_Streaming
Actually, if you have your storeowner run Chrome (other browsers will follow soon), you can use WebSockets (just for the storeowner's notification though), which allows you to have a constant connection open, and you can send data to the browser without the browser requesting anything.
There are a few websocket libraries for node.js, but i believe you can do it easily yourself using just a regular tcp connection.

Resources