Class: Friends::Graph

Inherits:
Object
  • Object
show all
Defined in:
lib/friends/graph.rb

Constant Summary collapse

DATE_FORMAT =
"%b %Y".freeze
SCALED_SIZE =
20

Instance Method Summary collapse

Constructor Details

#initialize(filtered_activities:, all_activities:, unscaled:) ⇒ Graph

Returns a new instance of Graph.

Parameters:

  • filtered_activities (Array<Friends::Activity>)

    a list of activities to highlight in the graph (may be the same as `all_activities`)

  • all_activities (Array<Friends::Activity>)

    a list of activities to graph

  • unscaled (Boolean)

    true iff we should show the absolute size of bars in the graph rather than a scaled version


15
16
17
18
19
20
21
22
23
24
# File 'lib/friends/graph.rb', line 15

def initialize(filtered_activities:, all_activities:, unscaled:)
  @filtered_activities = filtered_activities
  @all_activities = all_activities
  @unscaled = unscaled

  return if @all_activities.empty?

  @start_date = @all_activities.last.date
  @end_date = @all_activities.first.date
end

Instance Method Details

#outputArray<String>

Returns the output to print, with colors.

Returns:

  • (Array<String>)

    the output to print, with colors


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/friends/graph.rb', line 27

def output
  hash = to_h
  global_total = hash.max_by { |_, (_, val)| val }.last.last unless @unscaled || hash.empty?

  hash.map do |month, (filtered_count, total_count)|
    unless @unscaled
      # We want to use rationals for math so we can round up as well
      # as down (instead of int division), for more accurate graphing.
      # Floats are less trustworthy and could give results < 0 or > total_count
      filtered_count = Rational(filtered_count * SCALED_SIZE, global_total).round
      total_count = SCALED_SIZE
    end

    str = "#{month} |"
    str += Array.new(filtered_count) do |count|
      Paint["", color(count)]
    end.join
    if total_count > filtered_count
      str += Array.new(total_count - filtered_count) do |count|
        Paint["", color(filtered_count + count)]
      end.join + Paint["|", color(total_count + 1)]
    end

    str
  end.reverse!
end