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>");
});