Module: Timeprice::DataLoader

Defined in:
lib/timeprice/data_loader.rb

Overview

Loads and caches the bundled JSON data files. Override the search root by setting ‘TIMEPRICE_DATA_ROOT` in the environment or assigning DataLoader.data_root=.

Constant Summary collapse

SUPPORTED_SCHEMA_VERSION =
1
DEFAULT_DATA_ROOT =
File.expand_path("../../data", __dir__)

Class Method Summary collapse

Class Method Details

.clear_cache!void

This method returns an undefined value.

Drop in-memory caches of parsed data files.



32
33
34
35
# File 'lib/timeprice/data_loader.rb', line 32

def clear_cache!
  @cpi_cache = {}
  @fx_cache = {}
end

.data_rootString

Returns absolute path to the directory containing ‘cpi/` and `fx/`.

Returns:

  • (String)

    absolute path to the directory containing ‘cpi/` and `fx/`



18
19
20
# File 'lib/timeprice/data_loader.rb', line 18

def data_root
  ENV["TIMEPRICE_DATA_ROOT"] || @data_root || DEFAULT_DATA_ROOT
end

.data_root=(path) ⇒ void

This method returns an undefined value.

Override the data root and clear caches. Mostly useful in tests.

Parameters:

  • path (String)


25
26
27
28
# File 'lib/timeprice/data_loader.rb', line 25

def data_root=(path)
  @data_root = path
  clear_cache!
end

.load_cpi(country) ⇒ Hash

Load the CPI series for a supported country.

Parameters:

  • country (String)

Returns:

  • (Hash)

    parsed JSON with “monthly” / “annual” / metadata keys

Raises:



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/timeprice/data_loader.rb', line 43

def load_cpi(country)
  key = country.to_s.downcase
  code = country.to_s.upcase
  cpi_cache[[data_root, key]] ||= begin
    raise UnsupportedCountry, code unless Supported::COUNTRIES.include?(code)

    path = File.join(data_root, "cpi", "#{key}.json")
    unless File.exist?(path)
      raise DataNotFound, "CPI data file missing for #{code} (looked in #{path}). " \
                          "Check TIMEPRICE_DATA_ROOT or reinstall the gem."
    end

    parse_with_schema(path)
  end
end

.load_fx_year(year) ⇒ Hash

Load the FX rates for a year.

Parameters:

  • year (Integer, String)

Returns:

  • (Hash)

    parsed JSON with a “rates” map of date → currency → Float

Raises:



63
64
65
66
67
68
69
70
71
# File 'lib/timeprice/data_loader.rb', line 63

def load_fx_year(year)
  key = year.to_i
  fx_cache[[data_root, key]] ||= begin
    path = File.join(data_root, "fx", "usd", "#{key}.json")
    raise DataNotFound, "No FX data for year #{key}" unless File.exist?(path)

    parse_with_schema(path)
  end
end