3
votes

I am using a Twitter gem, however I was hoping to understand how to run it in the background after the page loads.

Currently I need to wait for the page to render, since the gem is working to query some tweets. Once the gem gets its response, the page loads.

However, I was hoping to display a "loading" GIF in my Twitter feed "div" tag, and once the Twitter information is retrieved, replace this GIF with the respective content.

I read several posts how to use a form and the ":remote => true" tag on the form in order to do AJAX calls that won't reload the respective page, but I don't want to force visitors to click a link in order to see Twitter tweets.

I'm using:

  • Ruby version: 1.8.7
  • Rails version: 3.0.9
1

1 Answers

4
votes

There are multiple ways of doing this; A fairly common practice and the way I would go about this is to use the the jQuery's $.ajax() to get data from the server and update the page.

Client-side:

  1. Load the page normally and show some kind of loading indicator.

  2. Make a call to $.ajax():

    $.ajax({
      type: "GET",
      url: userId + '/tweets', // i.e. tweets is a nested resource of user
      success: function(tweets){
        $('#loading_indicator').hide();
    
        // Use the tweets that are returned to update the DOM
        $.each(tweets, function(ndx, tweet) {
          $('#tweet_list').append('<li>'+tweet.body+<'/li'>);
        });
      }
    });
    

Server-side:

Have an action in a controller that sends out tweets as JSON to be consumed by the client-side success callback. Setup the routing for this action to be compatible with url in $.ajax():

class TweetsController < ApplicationController

  def show
    # collect tweets...
    render :json => @tweets
  end

end