RubyRails: How to access create action, without leaving index-Collection of common programming errors

You’ve got two big pieces of this:

  • Listening to the streaming API and creating objects
  • Updating the user’s view as new objects are created

The second bit can be done by some simple javascript polling, as in @AustinMullins’s answer.

The first bit should not be done in a controller – they are for responding to requests and deviating from that kind of job may end up with unexpected behavior or performance issues.

For example, I found that on a site that’s running on Phusion Passenger, the server would create a thread to handle a request, then kill it after a certain amount of time if it didn’t finish by itself, which of course it would not if the controller starts listening to a neverending input stream.

Instead, you should get a separate script that you can start from the command line. Here’s an example similar to what I’m using:

script/tracker.rb

#!/usr/bin/env ruby
ENV["RAILS_ENV"] ||= "production"
require File.dirname(__FILE__) + "/../config/environment"
TweetStream.configure do |config|
  config.consumer_key = TWITTER_COMSUMER_KEY
  config.consumer_secret = TWITTER_CONSUMER_SECRET
  config.oauth_token = TWITTER_OATH_TOKEN
  config.oauth_token_secret = TWITTER_OATH_TOKEN_SECRET
end

client = TweetStream::Client.new
client.track(*Keyword.pluck(:name)).each do |status|
  Tweet.create(status.text)
end

script/tracker_ctl

#!/usr/bin/env ruby
require 'rubygems'
require 'daemons'
Daemon.new('tracker.rb')

Now, you could ssh into your server and run script/tracker_ctl start or script/tracker_ctl stop. But what you probably want to do is make a controller action issue those commands instead.