Use a series with recent data
This commit is contained in:
parent
f7e7b89bfb
commit
01684a7c3c
@ -1,6 +1,6 @@
|
||||
# This configuration was generated by
|
||||
# `rubocop --auto-gen-config`
|
||||
# on 2020-01-01 01:01:20 -0500 using RuboCop version 0.78.0.
|
||||
# on 2020-01-08 20:39:50 -0500 using RuboCop version 0.78.0.
|
||||
# The point is for the user to remove these configuration records
|
||||
# one by one as the offenses are removed from the code base.
|
||||
# Note that changes in the inspected code, or installation of new
|
||||
|
@ -6,30 +6,40 @@ require 'net/https'
|
||||
require 'uri'
|
||||
|
||||
class CPIFetcher
|
||||
DEFAULT_CPI_SERIES_URL = File.join(
|
||||
'https://api.bls.gov',
|
||||
'publicAPI/v2/timeseries/data/CUUSA210SA0'
|
||||
)
|
||||
private_constant :DEFAULT_CPI_SERIES_URL
|
||||
attr_reader :url, :bls_token
|
||||
private :url, :bls_token
|
||||
|
||||
def initialize
|
||||
@url = URI(ENV['CPI_SERIES_URL'] || DEFAULT_CPI_SERIES_URL)
|
||||
@bls_token = ENV.fetch('BLS_TOKEN')
|
||||
end
|
||||
|
||||
def cpi
|
||||
resp = fetch_raw_response
|
||||
return nil unless resp['Results']['series']
|
||||
|
||||
last_cpi_value(resp['Results']['series'].first['data'])
|
||||
latest_cpi_value(resp['Results']['series'].first['data'])
|
||||
end
|
||||
|
||||
private def last_cpi_value(data)
|
||||
data
|
||||
.sort { |a, b| a['year'] <=> b['year'] }
|
||||
.then { |d| d.last['value'] }
|
||||
private def url
|
||||
@url ||= URI(ENV['CPI_SERIES_URL'] || File.join(
|
||||
'https://api.bls.gov',
|
||||
'publicAPI/v2/timeseries/data/'
|
||||
))
|
||||
end
|
||||
|
||||
private def series_id
|
||||
@series_id ||= ENV.fetch(
|
||||
'CPI_SERIES_ID', 'CUURS000SA0,CUUSS000SA0'
|
||||
).split(/[, ]/).map(&:strip).reject(&:empty?)
|
||||
end
|
||||
|
||||
private def start_year
|
||||
@start_year ||= ENV.fetch('CPI_SERIES_START_YEAR', '2014')
|
||||
end
|
||||
|
||||
private def end_year
|
||||
@end_year ||= ENV.fetch('CPI_SERIES_END_YEAR', Time.now.year.to_s)
|
||||
end
|
||||
|
||||
private def bls_token
|
||||
@bls_token ||= ENV.fetch('BLS_TOKEN')
|
||||
end
|
||||
|
||||
private def latest_cpi_value(data)
|
||||
data.find { |d| d['latest'] == 'true' }.fetch('value')
|
||||
end
|
||||
|
||||
private def fetch_raw_response
|
||||
@ -40,8 +50,18 @@ class CPIFetcher
|
||||
end
|
||||
|
||||
private def build_request
|
||||
Net::HTTP::Get.new(url)
|
||||
Net::HTTP::Post.new(url)
|
||||
.tap { |r| r['Authorization'] = "token #{bls_token}" }
|
||||
.tap { |r| r['Content-Type'] = 'application/json' }
|
||||
.tap { |r| r.body = JSON.generate(build_request_body) }
|
||||
end
|
||||
|
||||
private def build_request_body
|
||||
{
|
||||
'seriesid' => series_id,
|
||||
'startyear' => start_year,
|
||||
'endyear' => end_year
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user