How to create a live feed using Rails

I am trying to create a live channel block that identifies the latest data added to the forum discussion and automatically updates the block on another page with the latest posts on this forum. I use Ruby on Rails and I would really appreciate any help on this.

(If my question is not clear, I hope I can be more specific with one of these examples). I'm trying to create something similar to the current twitter updates that are currently in blogs, or will not mind the Twitter homepage, which automatically updates. I assume that the Twitter homepage will use some kind of polling function.

Any help on creating one of them would be awesome

+3
source share
1 answer

These sites do this by regularly polling the server using the XmlHttpRequests created by javascript. This is made possible by the function.setInterval

The shortest version is something like this (jQuery, but translating the library would be simple):

setInterval(function() {
  $.getJSON('/posts.json', function(posts) {
    // code to remove old posts
    // code to insert new posts
  });
}, 5000);

5000 is the time, in milliseconds, between a function call.

You will then have your message controller, just return the latest messages:

class PostsController < ApplicationController
  @posts = Post.find(:all, :order => 'created_at desc')

  respond_to do |format|
    format.html
    format.json { render :json => @posts.to_json }
  end
end
+5
source

Source: https://habr.com/ru/post/1731271/


All Articles