fluke/devops-client/lib/devops-client/output/base.rb
2015-07-21 20:32:41 +04:00

87 lines
2.0 KiB
Ruby

require "terminal-table"
require "csv"
require "json"
module Output
class Base
attr_reader :options
def initialize(data_to_output, options={})
@data, @options = data_to_output, options
end
def output(preferred_options)
@options = @options.merge(preferred_options)
case options[:format]
when CommonOptions::TABLE_FORMAT
table
when CommonOptions::JSON_FORMAT
json
when CommonOptions::CSV_FORMAT
csv
end
end
def json
JSON.pretty_generate(@data)
end
private
def output_type
@data.kind_of?(Array) ? :list : :show
end
def outputting_list?
output_type == :list
end
def with_num?
outputting_list?
end
def create_table headers, rows, title=nil, with_num=true, separator=false
return nil if headers.nil? or rows.nil?
if with_num
headers.unshift(I18n.t("output.table_header.number"))
rows.each_with_index {|row, i| row.unshift(i + 1)}
end
table = Terminal::Table.new do |t|
titles = ["#{I18n.t("output.table_header.api_version")}: #{self.options[:api]}",
"#{title}"
]
t.title = titles.join( "\n" )
t.headings = headers
t.add_row rows[0]
rows[1..-1].each do |r|
t.add_separator if separator
t.add_row r
end
end
table
end
def create_csv headers, rows, with_num=true, separator=":"
if with_num
headers.unshift(I18n.t("output.table_header.number"))
rows.each_with_index {|row, i| row.unshift(i + 1)}
end
c = CSV.new("", {col_sep: separator, headers: true})
c << headers
rows.each{|r| c << r}
c.string
end
def headers_and_rows(records, fields_to_output)
headers = fields_to_output.map { |field| I18n.t("output.table_header.#{field}") }
rows = records.map do |record|
fields_to_output.map { |field| record[field] }
end
[headers, rows]
end
end
end