Class: Timeprice::CLI::Presenters::Compare

Inherits:
Object
  • Object
show all
Includes:
Formatting
Defined in:
lib/timeprice/cli/presenters/compare.rb

Overview

Renders a CompareResult for the CLI in text and JSON formats.

Instance Method Summary collapse

Methods included from Formatting

#fmt_money, #fmt_rate, #round_money, #with_commas

Constructor Details

#initialize(result) ⇒ Compare

Returns a new instance of Compare.



13
14
15
# File 'lib/timeprice/cli/presenters/compare.rb', line 13

def initialize(result)
  @result = result
end

Instance Method Details

#json_hashObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/timeprice/cli/presenters/compare.rb', line 17

def json_hash
  base = @result.to_h.merge(
    amount: round_money(@result.amount, @result.to_currency),
    original_amount: round_money(@result.original_amount, @result.from_currency),
    converted_amount: round_money(@result.converted_amount, @result.to_currency),
    fx_rate: @result.fx_rate.to_f.round(6),
    cpi_ratio: @result.cpi_ratio.to_f.round(6)
  )
  if @result.forecast
    fc = @result.forecast
    base[:forecast] = fc.merge(
      low: round_money(fc[:low], @result.to_currency),
      high: round_money(fc[:high], @result.to_currency)
    )
  else
    base.delete(:forecast)
  end
  base
end

#text_linesObject

Headline + left-to-right chain so the FX + CPI composition reads naturally.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/timeprice/cli/presenters/compare.rb', line 38

def text_lines
  final     = "#{fmt_money(@result.amount, @result.to_currency)} #{@result.to_currency}"
  original  = "#{fmt_money(@result.original_amount, @result.from_currency)} #{@result.from_currency}"
  converted = "#{fmt_money(@result.converted_amount, @result.to_currency)} #{@result.to_currency}"
  step1     = "fx @ #{fmt_rate(@result.fx_rate)}"
  step2     = "inflate x#{format("%.4f", @result.cpi_ratio)} #{@result.country}"
  width     = [step1.length, step2.length].max
  headline = if @result.forecast
               "#{final}  in #{@result.to_date}  (forecast)"
             else
               "#{final}  in #{@result.to_date}"
             end
  lines = [
    headline,
    "  #{original} (#{@result.from_date})",
    format("    -> %-#{width}s -> %s (%s)", step1, converted, @result.from_date),
    format("    -> %-#{width}s -> %s (%s, %s)", step2, final, @result.to_date,
           Granularity.humanize(@result.granularity)),
  ]
  @result.forecast ? lines + forecast_lines(final) : lines
end