Class: Fp::Output

Inherits:
Object
  • Object
show all
Defined in:
lib/fp/output.rb

Overview

Output formatting for CLI responses Follows Fizzy CLI conventions: { ok: true/false, data: ..., error: ... }

Instance Method Summary collapse

Constructor Details

#initialize(json: false) ⇒ Output

Returns a new instance of Output.



9
10
11
# File 'lib/fp/output.rb', line 9

def initialize(json: false)
  @json = json
end

Instance Method Details

#csv(headers, rows) ⇒ Object



62
63
64
65
66
67
68
69
# File 'lib/fp/output.rb', line 62

def csv(headers, rows)
  require 'csv'
  csv_string = CSV.generate do |csv|
    csv << headers
    rows.each { |row| csv << row }
  end
  puts csv_string
end

#error(message, status: nil) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/fp/output.rb', line 26

def error(message, status: nil)
  if @json
    result = { ok: false, error: message }
    result[:status] = status if status
    puts JSON.pretty_generate(result)
  else
    warn "Error: #{message}"
  end
end

#json?Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/fp/output.rb', line 13

def json?
  @json
end

#success(data, summary: nil) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/fp/output.rb', line 17

def success(data, summary: nil)
  if @json
    puts JSON.pretty_generate({ ok: true, data: data })
  else
    yield if block_given?
    puts summary if summary
  end
end

#table(headers, rows) ⇒ Object



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
# File 'lib/fp/output.rb', line 36

def table(headers, rows)
  return if rows.empty?

  if @json
    # For JSON output, return data as array of hashes
    data = rows.map { |row| headers.zip(row).to_h }
    puts JSON.pretty_generate({ ok: true, data: data })
  else
    # ASCII table
    widths = headers.map.with_index do |header, i|
      [header.to_s.length, *rows.map { |r| r[i].to_s.length }].max
    end

    separator = '+' + widths.map { |w| '-' * (w + 2) }.join('+') + '+'
    format_row = lambda do |row|
      '| ' + row.map.with_index { |cell, i| cell.to_s.ljust(widths[i]) }.join(' | ') + ' |'
    end

    puts separator
    puts format_row.call(headers)
    puts separator
    rows.each { |row| puts format_row.call(row) }
    puts separator
  end
end