Class: Portfolio::Formatter

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/portfolio/formatter.rb

Instance Method Summary collapse

Instance Method Details

#format_portfolio(portfolio) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/portfolio/formatter.rb', line 31

def format_portfolio(portfolio)
  portfolio.map! do |investment|
    # Work out price paid, value, current stock price and profit for
    # this investment:
    symbol = investment['stock']
    current_price = StockPrices.instance.get_stock(symbol).ask
    total_paid = (investment['amount_bought'].to_f * investment['price_paid'].to_f) + investment['commission_paid'].to_f
    total_value = investment['amount_bought'].to_f * current_price
    profit = (total_value - total_paid).round(2)
    
    # If profit is negative, highlight as red:
    if profit < 0.00
      profit = profit.to_s.red
    # If profit is positive, highlight as green:
    elsif profit > 0.00
      profit = profit.to_s.green
    # Otherwise, don't highlight it - no profit or loss:
    else
      profit = profit.to_s
    end
    
    {
      symbol: symbol,
      current_price: current_price,
      number_owned: investment['amount_bought'],
      price_paid: investment['price_paid'],
      commission: investment['commission_paid'],
      profit: profit,
    }
  end
end

#output_table(title, columns, data, headings = nil) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/portfolio/formatter.rb', line 8

def output_table(title, columns, data, headings = nil)
  # Format data correctly for table:
  data.map! do |row|
    new_row = []
    
    columns.each do |col|
      new_row << row[col]
    end
    
    new_row
  end
  
  # Create table with headings if some are passed in (or without if nil):
  if headings.nil?
    table = Terminal::Table.new(rows: data, title: title)
  else
    table = Terminal::Table.new(rows: data, title: title, headings: headings)
  end
  
  # Output table:
  puts table
end