Class: Timeprice::CpiLookup

Inherits:
Object
  • Object
show all
Defined in:
lib/timeprice/cpi_lookup.rb

Overview

Resolves CPI keys (“YYYY”, “YYYY-MM”, or “YYYY-Qn”) to a CpiPoint against a single country’s parsed CPI data hash. Knowing the JSON shape (“monthly” / “quarterly” / “annual” string keys) is isolated here — Inflation just asks for points.

Constant Summary collapse

QUARTER_RE =
/\A(\d{4})-Q([1-4])\z/

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ CpiLookup

Returns a new instance of CpiLookup.



18
19
20
21
22
23
# File 'lib/timeprice/cpi_lookup.rb', line 18

def initialize(data)
  @data = data
  @monthly   = data.dig("series", "monthly")   || {}
  @quarterly = data.dig("series", "quarterly") || {}
  @annual    = data.dig("series", "annual")    || {}
end

Instance Method Details

#at(key) ⇒ CpiPoint

Daily keys are accepted and silently resolved at month grain — CPI is published monthly at best, so the day is dropped before lookup. The returned granularity reflects what the monthly cascade actually found (monthly / quarterly fallback / annual fallback), not “daily”.

Parameters:

  • key (String)

    “YYYY”, “YYYY-MM”, “YYYY-Qn”, or “YYYY-MM-DD”

Returns:

Raises:

  • (DataNotFound)

    if no CPI value covers ‘key`

  • (ArgumentError)

    on malformed ‘key`



34
35
36
37
38
39
40
41
42
43
# File 'lib/timeprice/cpi_lookup.rb', line 34

def at(key)
  key = key.to_s
  case key
  when QUARTER_RE              then quarterly_or_fallbacks(key)
  when /\A\d{4}-\d{2}-\d{2}\z/ then monthly_or_fallbacks(key[0, 7])
  when /\A\d{4}-\d{2}\z/       then monthly_or_fallbacks(key)
  when /\A\d{4}\z/             then annual_or_derived(key)
  else fail ArgumentError, "Invalid date format: #{key.inspect} (use YYYY, YYYY-MM, YYYY-Qn, or YYYY-MM-DD)"
  end
end