Class: Equalshares::CLI::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/equalshares/cli/formatter.rb

Overview

Renders a computation Result for a given instance as human-readable text, CSV or JSON. Each renderer returns a String (including the trailing newline).

Instance Method Summary collapse

Constructor Details

#initialize(instance, result) ⇒ Formatter

Returns a new instance of Formatter.



11
12
13
14
# File 'lib/equalshares/cli/formatter.rb', line 11

def initialize(instance, result)
  @instance = instance
  @result = result
end

Instance Method Details

#csvObject



28
29
30
31
32
33
34
35
36
# File 'lib/equalshares/cli/formatter.rb', line 28

def csv
  CSV.generate do |csv|
    csv << %w[project_id name cost votes effective_vote_count]
    @result.winners.each do |c|
      csv << [c, project(c, "name"), project(c, "cost"),
              @instance.approvers[c].length, @result.effective_vote_count(c)]
    end
  end
end

#humanObject



38
39
40
41
42
43
44
45
# File 'lib/equalshares/cli/formatter.rb', line 38

def human
  lines = summary_lines + [""]
  rows = @result.winners.map do |c|
    [c, truncate(project(c, "name"), 50), project(c, "cost"),
     @instance.approvers[c].length.to_s, format_number(@result.effective_vote_count(c))]
  end
  "#{(lines + table(%w[id name cost votes eff.votes], rows)).join("\n")}\n"
end

#jsonObject



24
25
26
# File 'lib/equalshares/cli/formatter.rb', line 24

def json
  "#{JSON.pretty_generate(@result.to_h)}\n"
end

#render(format) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/equalshares/cli/formatter.rb', line 16

def render(format)
  case format
  when "json" then json
  when "csv" then csv
  else human
  end
end