Skip to content

Instantly share code, notes, and snippets.

@jstn
Created September 29, 2012 21:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstn/3805192 to your computer and use it in GitHub Desktop.
Save jstn/3805192 to your computer and use it in GitHub Desktop.
howisobamadoing.com / howisromneydoing.com
# howisobamadoing.com / howisromneydoing.com
# (c) justinouellette.com MMXII
require 'rubygems'
require 'sinatra'
CACHE_TIME = 3600 # one hour
OBAMA_DATA_PATH = 'obama.txt'
ROMNEY_DATA_PATH = 'romney.txt'
get '/' do
# are we obama or romney?
@romney = request.env['SERVER_NAME'].include?('romney')
data_file_path = @romney ? ROMNEY_DATA_PATH : OBAMA_DATA_PATH
# get the data for the first time if necessary
update_data unless File.exists?(data_file_path)
# how old is the data?
data_file = File.new(data_file_path)
lmt = data_file.mtime
modified_seconds_ago = Time.new.to_i - lmt.to_i
# update the data if it's too old
if modified_seconds_ago > CACHE_TIME
data_file.close
update_data
data_file = File.new(data_file_path)
end
# get the number
@number = data_file.read.to_i
data_file.close
# http headers for cache control
expires(CACHE_TIME - modified_seconds_ago)
etag(lmt.to_s + data_file_path)
last_modified(lmt)
# hc svnt dracones
"The chance of #{@romney ? 'Romney' : 'Obama'} winning is #{@number}%"
end
def update_data
# get fivethirtyeight and find the interesting js file
html_538 = `curl -s fivethirtyeight.blogs.nytimes.com`
js_match = /dataUrl: "(.+top\.js)/.match(html_538)
return unless js_match
# get the interesting js file and find our numbers
js_538 = `curl -s #{js_match[1]}`
forecast_match = /forecast":\[\["[\d|-]+",[\d|\.]+,[\d|\.]+,([\d|\.]+),([\d|\.]+)/.match(js_538)
return unless forecast_match
# round the numbers and write them to disk
`echo #{forecast_match[1].to_f.round} > #{OBAMA_DATA_PATH}`
`echo #{forecast_match[2].to_f.round} > #{ROMNEY_DATA_PATH}`
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment