Skip to content

Instantly share code, notes, and snippets.

@lukeredpath
Created November 19, 2009 01:30
Show Gist options
  • Save lukeredpath/238456 to your computer and use it in GitHub Desktop.
Save lukeredpath/238456 to your computer and use it in GitHub Desktop.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<% if @from %>
<title>Tweetstream: <%= @hashtag %>, by <%= @from %></title>
<% else %>
<title>Tweetstream: <%= @hashtag %></title>
<% end %>
</head>
<body>
<% if @from %>
<h1>Tweetstream: <%= @hashtag %>, by <%= @from %></h1>
<% else %>
<h1>Tweetstream: <%= @hashtag %></h1>
<% end %>
<ul>
<% @tweets.each do |tweet| %>
<li class="tweet">
<%= tweet.text %>
</li>
<% end %>
</ul>
</body>
#!/usr/bin/env ruby
require 'twitter'
require 'erb'
require 'trollop'
options = Trollop.options do
opt :tag, "Hashtag to use as a filter",
:type => :string, :required => true
opt :from, "Restrict to tweets from a specific user",
:type => :string
opt :template, "ERB template used to render the stream",
:type => :string, :required => true
opt :output, "Output to this file",
:type => :string
end
class Tweetstream
def initialize(hashtag, from = nil)
@hashtag, @from = sanitize_hashtag(hashtag), from
end
def render(template_path)
perform_search!
template = File.read(template_path)
ERB.new(template).result(binding)
end
private
def sanitize_hashtag(hashtag)
"##{hashtag}".squeeze('#')
end
def perform_search!
query = Twitter::Search.new(@hashtag)
query = query.from(@from) if @from
@tweets = query.map { |tweet| tweet }
end
end
stream = Tweetstream.new(options[:tag], options[:from])
output = stream.render(options[:template])
if options[:output]
File.open(options[:output], 'w') { |io| io.write(output) }
else
puts output
end
# prints to STDOUT by default, optional -o switch to specify output file
$ ruby tweetstream.rb -t 'myhashtag' -f 'lukeredpath' -e 'path/to/template.erb'
Options:
--tag, -t <s>: Hashtag to use as a filter
--from, -f <s>: Restrict to tweets from a specific user
--template, -e <s>: ERB template used to render the stream
--output, -o <s>: Output to this file
--help, -h: Show this message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment