Extract bits into a separate file for offline generation

This commit is contained in:
Dan Buch 2015-09-06 09:15:49 -04:00
parent 1f789f1674
commit 8f56f32d73
4 changed files with 47 additions and 25 deletions

21
app.rb Normal file
View File

@ -0,0 +1,21 @@
require 'sinatra/base'
require_relative 'cpi_fetcher'
class App < Sinatra::Base
get '/' do
current_cpi = fetcher.cpi
halt 502 unless current_cpi
expires 300, :public, :must_revalidate
content_type :text
"#{current_cpi}\n"
end
run! if app_file == $PROGRAM_FILE
private
def fetcher
@fetcher ||= CPIFetcher.new
end
end

View File

@ -1,3 +1,3 @@
require './cpi_feed' require './app'
run CPIFeed run App

View File

@ -1,23 +0,0 @@
require 'sinatra/base'
require 'faraday'
require 'json'
class CPIFeed < Sinatra::Base
DEFAULT_CPI_SERIES_URL = 'http://api.bls.gov/publicAPI/v2/timeseries/data/CUUSA210SA0'
get '/' do
resp = JSON.parse(Faraday.get(cpi_series_url).body)
halt 502 unless resp['Results']['series']
expires 300, :public, :must_revalidate
content_type :csv
"#{resp['Results']['series'].first['data'].first['value']}\n"
end
def cpi_series_url
ENV['CPI_SERIES_URL'] || DEFAULT_CPI_SERIES_URL
end
run! if app_file == $PROGRAM_FILE
end

24
cpi_fetcher.rb Normal file
View File

@ -0,0 +1,24 @@
require 'faraday'
require 'json'
class CPIFetcher
DEFAULT_CPI_SERIES_URL = 'http://api.bls.gov/publicAPI/v2/timeseries/data/CUUSA210SA0'
attr_reader :cpi_series_url
def initialize
@cpi_series_url = (ENV['CPI_SERIES_URL'] || DEFAULT_CPI_SERIES_URL)
end
def cpi
resp = JSON.parse(Faraday.get(cpi_series_url).body)
return nil unless resp['Results']['series']
resp['Results']['series'].first['data'].first['value']
end
end
if $PROGRAM_NAME == __FILE__
puts CPIFetcher.new.cpi
exit 0
end