Monday, May 13, 2024
HomeRuby On RailsRails HTML Polling With out Writing JavaScript?

Rails HTML Polling With out Writing JavaScript?


Write easy HTML polling by writing Ruby on Rails ONLY.


Man pulling rope

If you happen to did Rails, you’ve most likely coded one or two polling mechanisms again within the day. Halfway by way of writing it, an annoying feeling begins creeping in when you must write that additional JavaScript after coding the Rails half on the server. If you happen to get that feeling, (and even should you don’t), there may be now a approach to do it with out really writing any JS code. First, let’s dive into thought of polling under.

What’s polling?

Polling is a course of when a consumer (our browser on this case) regularly sends requests to a server to verify if updates can be found. Polling is what is named pull expertise. It’s usually used to emulate push expertise. Earlier than we go on, let’s describe these phrases:

Pull expertise

Definition: Preliminary request for knowledge originates from a consumer, after which is responded to.
Instance: An internet browser requests an internet web page.

Push expertise (often known as push notifications)

Definition: A server publishes knowledge, and a consumer that’s subscribed is receiving knowledge.
Instance: A electronic mail server transmits an electronic mail to an electronic mail consumer.

So, as a substitute of doing publish / subscribe mechanism, the place the server sends knowledge updates and we pay attention for these updates, we’re going to repeatedly ask the server whether or not modifications did really occur.

Easy methods to do polling in Rails?

OK, now that we defined what polling is, let’s get right down to enterprise. To be able to do polling in Rails you will have to write down 2 issues:

  1. Controller motion that will probably be polled and the response/view it returns
  2. JavaScript that may periodically verify your controller motion for modifications and make obligatory updates within the UI

First half is fairly simple. Let’s say we’ve an internet site that present’s films and their rankings. Ranking of a film modifications continuously, and we wish to preserve the person up to date for any ranking change that occurs. For this case, we are going to create a ranking motion contained in the Motion pictures controller.


class MoviesController < ApplicationController
  
  def ranking
    @ranking = @film.ranking

    render partial: 'movie_rating'
  finish
finish

Then, we will create a partial for the film ranking like this, so we will present it properly to the person:


Film ranking: <%= @ranking %>

Second half generally is a little annoying typically. We have to write JavaScript on our frontend that may repeatedly question the server motion we outlined. However, it additionally must replace the web page so the modifications could be mirrored.



<div id="ranking">Loading ranking...</div>

<script>
  const checkRating = () => {
    fetch("<%= movie_rating_path(@film) %>")
      .then((response) => response.textual content())
      .then((response) => {
        doc.getElementById("ranking").innerHTML = response
      })
  }
  setInterval(checkRating, 2000)
</script>

Right here we outlined a checkRating (line 6) operate that may get known as each 2 seconds by the setInterval at line 14. On the line 7, we’re telling it to fetch a ranking of a film by specifying its ID within the request URL.

And voilà 🎉, should you go to your film web page and open the Community tab in your browser, you need to see that request in direction of ranking motion is dispatched each 2 seconds.

However how do I ballot with out JavaScript?

Maintain your horses 🎠, we’re getting there. You are able to do easy polling with the brand new model of the render_async gem! To be able to do that, you’ll want to put in the gem inside your Rails software and put this snippet in your software.html.erb file.

<%= content_for :render_async %>

This snippet will load the JavaScript code for us in order that we don’t have to write down it ourselves. So, it’s not precisely with out it, it’s simply that we don’t have to write down it ourselves.

We are going to preserve movies_controller.rb and _movie_rating.html.erb recordsdata from the earlier instance, and we are going to solely edit present.html.erb to appear like this:



<%= render_async movie_rating_path(@film), interval: 2000 %>

Wait, that is it? Yep, that’s it, congrats 🎉! This piece of code will generate JavaScript that may fetch film ranking each 2 seconds. How neat and superior 😌. If you happen to go to your film web page now, its ranking ought to present up and will continuously be up to date by polling.

BONUS ROUND

That’s not all you are able to do with it. You’ll be able to throw in some error dealing with in there too, additionally with none JS code to be written:


<%= render_async movie_rating_path(@film), interval: 2000, error_message:
"Could not load ranking :(" %>

Your response whereas studying this: WOW, I can get an error message to point out up too 🤯? The place can I check out this gem?

Proper right here my buddy. You’re welcome ❤️.

Polling function was just lately launched within the 2.1.0 model of the gem and it’s prepared for use by the group. In case you are utilizing polling in your app, you’ll be able to check out this function of the gem.

render_async has been round for a very long time, it’s utilized in merchandise like Codetriage (see concern on GitHub by Richard Schneeman and it’s been praised by Nate Berkopec on Twitter:

You may also learn the unique weblog put up that made render_async well-known and see his unique use case on the Semaphore CI weblog.

If you happen to appreciated what you noticed, please 👏 and unfold the phrase. Additionally, take a look at my web site and comply with me. I’ll be posting extra of Rails and JavaScript associated articles, so click on “Observe” and keep tuned 📹.

Additionally, retweeting that is an superior approach to assist unfold the phrase with your mates:

Cheers! 🍻



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments