Class: EasyCols::Formatter

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

Constant Summary collapse

SUPPORTED_OUTPUT_FORMATS =
%w[csv tsv table tbl plain same].freeze

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Formatter

Returns a new instance of Formatter.



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/easy_cols/formatter.rb', line 9

def initialize(options = {})
  @options = {
    format: 'same',
    separator: ' , ',
    show_header: true,
    table_mode: false
  }.merge(options)

  # Use pipe separator in table mode if separator wasn't explicitly provided
  if (@options[:table_mode] || @options[:format] == 'table' || @options[:format] == 'tbl') && !options.key?(:separator)
    @options[:separator] = ' | '
  end
end

Instance Method Details

#format(data, selected_indices) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/easy_cols/formatter.rb', line 23

def format(data, selected_indices)
  return '' if data.empty? || selected_indices.empty?

  output_format = @options[:format]

  case output_format
  when 'csv' then format_csv(data, selected_indices)
  when 'tsv' then format_tsv(data, selected_indices)
  when 'table', 'tbl' then format_table(data, selected_indices)
  when 'plain' then format_plain(data, selected_indices)
  when 'same', nil then format_default(data, selected_indices)
  else
    raise FormatError, "Unsupported output format: #{output_format}"
  end
end