Rails HTML Polling Without Writing JavaScript?
--
Write simple HTML polling by writing Ruby on Rails ONLY.
If you did Rails, you’ve probably coded one or two polling mechanisms back in the day. Midway through writing it, an annoying feeling starts creeping in when you have to write that extra JavaScript after coding the Rails part on the server. If you get that feeling, (and even if you don’t), there is now a way to do it without actually writing any JS code. First, let’s dive into idea of polling below.
What is polling?
Polling is a process when a client (our browser in this case) continually sends requests to a server to check if updates are available. Polling is what is called pull technology. It’s often used to emulate push technology. Before we go on, let’s describe these terms:
Pull technology
Definition: Initial request for data originates from a client, and then is responded to.
Example: A web browser requests a web page.
Push technology (also known as push notifications)
Definition: A server publishes data, and a client that is subscribed is receiving data.
Example: A email server transmits an email to an email client.
So, instead of doing publish / subscribe mechanism, where the server sends data updates and we listen for those updates, we are going to repeatedly ask the server whether changes did actually happen.
How to do polling in Rails?
OK, now that we explained what polling is, let’s get down to business. In order to do polling in Rails you will need to write 2 things:
- Controller action that will be polled and the response/view it returns
- JavaScript that will periodically check your controller action for changes and make necessary updates in the UI
First part is pretty straightforward. Let’s say we have a website that show’s movies and their ratings. Rating of a movie changes constantly, and we want to keep the user updated for any rating change that happens. For this case, we will create a rating action inside the Movies controller.