lib/legitable/table.rb in legitable-0.2.0 vs lib/legitable/table.rb in legitable-0.3.0
- old
+ new
@@ -1,39 +1,46 @@
-require 'ostruct'
+require "ostruct"
module Legitable
class Table
attr_reader :rows, :headers, :delimiter, :separator, :format, :style
- def initialize(alignment: {}, delimiter: ' | ', separator: '-', style: nil, &block)
+ def initialize(alignment: {}, delimiter: " | ", separator: "-", style: nil, &block)
@rows = []
@headers = []
@format = {}
@formatters = {}
@alignment = alignment
@delimiter = delimiter
@separator = separator
@style = style
if style == :markdown
- @delimiter = ' | '
- @separator = '-'
+ @delimiter = " | "
+ @separator = "-"
end
- self.instance_eval(&block) unless block.nil?
+ instance_eval(&block) unless block.nil?
end
- def <<(row)
- initialize_headers(row) if headers.empty?
- add_row row
+ def <<(data)
+ case data
+ when Array
+ data.each { |row| self << row }
+ when Hash
+ initialize_headers(data) if headers.empty?
+ add_row data
+ when Enumerable
+ data.each { |row| self << row }
+ end
self
end
def to_s
- <<-EOS
-#{render_headers}
-#{render_rows}
+ <<~EOS
+ #{render_headers}
+ #{render_rows}
EOS
end
private
@@ -47,18 +54,17 @@
)
end
end
def add_row(row)
- rows << headers.inject({}) do |memo, header|
+ rows << headers.each_with_object({}) do |header, memo|
formatter = format[header].formatter
value = formatter.call(row[header].to_s).to_s
if format[header].width < value.length
format[header].width = value.length
end
memo[header] = value
- memo
end
end
def render_headers
headers.map do |header|
@@ -83,30 +89,30 @@
def render_separator
if style == :markdown
headers.map do |header|
separator * format[header].width
- end.join('-|-')
+ end.join("-|-")
else
separator * row_width
end
end
def render_cell(header, value)
cell_width = format[header].width
- (format[header].align == :right) ?
- value.rjust(cell_width, ' ') :
- value.to_s + (' ' * (cell_width - value.to_s.length))
+ format[header].align == :right ?
+ value.rjust(cell_width, " ") :
+ value.to_s + (" " * (cell_width - value.to_s.length))
end
def formatting(header, &block)
- @formatters[header] = block ? block : default_formatter
+ @formatters[header] = block || default_formatter
end
def default_formatter
- @default_formatter ||= Proc.new {|value| value.to_s }
+ @default_formatter ||= proc { |value| value.to_s }
end
def formatting_headers(&block)
@header_formatter = block
end
@@ -114,9 +120,9 @@
def header_formatter
@header_formatter ||= default_header_formatter
end
def default_header_formatter
- @default_header_formatter ||= Proc.new { |header| header.to_s.upcase }
+ @default_header_formatter ||= proc { |header| header.to_s.upcase }
end
end
end