From 01684a7c3cb1d5d5885912fc4f6fb43e10a9fbe1 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Wed, 8 Jan 2020 20:40:43 -0500 Subject: [PATCH] Use a series with recent data --- .rubocop_todo.yml | 2 +- cpi_fetcher.rb | 58 +++++++++++++++++++++++++++++++---------------- 2 files changed, 40 insertions(+), 20 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index f94de40..55679db 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -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 diff --git a/cpi_fetcher.rb b/cpi_fetcher.rb index 069f48d..7b9b866 100644 --- a/cpi_fetcher.rb +++ b/cpi_fetcher.rb @@ -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 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 last_cpi_value(data) - data - .sort { |a, b| a['year'] <=> b['year'] } - .then { |d| d.last['value'] } + 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