0

I have a controller that renders fetch.js.erb if the user exists. What I want to do is render this file, and then call update_tweets and save on the user object. Currently, update_tweets and save are called before the javascript is rendered. Thus, the faye messages are being published before the subscription is setup. How do I force the javascript to execute earlier? Another option would be to somehow call @user.update_tweets in a nonblocking manner, but I'm not sure how to do this.

user_controller.rb

class UserController < ApplicationController

  def fetch
    unless @user = User.find_by_name(params["user"])
      begin
        if Twitter.user(params["user"]).protected?
          render :private_user and return
        else
          @user = User.new(:name => params["user"])
        end
      rescue Twitter::Error::NotFound
        render :dne_user and return
      end
    end

    render :fetch
    @user.update_tweets
    @user.save
  end

end

user.rb

class User

  after_save do |user|
    puts "i've been saved!! sleeping now"
    sleep(20)
    user.tweets.each do |tweet|
      message = {:channel => "/" + self.name, :data => tweet.text }
      uri = URI.parse("http://localhost:9292/faye")
      puts Net::HTTP.post_form(uri, :message => message.to_json)
    end
  end

end

fetch.js.erb

client = new Faye.Client("http://localhost:9292/faye");
alert("running");
client.subscribe("/<%= @user["name"] %>", function(data) {
  $('#tweets').append("<p>"+data+"</p>");
});

1 Answers1

0

The render call will create the output when called, but it won't be sent to the browser until your controller returns.

That said, why are you doing it that way? You should really do the save of the user before calling render and let the render method serve the tweets that are already loaded, you are trying to use faye to solve something that is easier to solve in a different way, if you are already serving to the client, in fetch.js.erb, just serve the content from it.

As a side note, you might want to use @user.id as the channel instead of name, there could be people with the same name, who would get messages for other people with the same name, unless that's what you intended to do.

Pablo Fernandez heelhook
  • 11,985
  • 3
  • 21
  • 20