class Tableware::Parser

Constants

ROW_END
ROW_START

Public Instance Methods

arrays(input) click to toggle source
# File lib/tableware/parser.rb, line 10
def arrays(input)
  make_arrays(input)
end
hashes(input) click to toggle source
# File lib/tableware/parser.rb, line 14
def hashes(input)
  items = make_arrays(input)
  raise TableWithoutHeaderError, 'Sorry, only text tables with header rows can be turned into hashes' unless @headers
  items.map! { |row| @headers.zip(row).to_h }
end

Private Instance Methods

make_arrays(input) click to toggle source
# File lib/tableware/parser.rb, line 20
        def make_arrays(input)
  lines = prepare_lines(input)
  lines[@data_start..-1].map do |line|
    parsed = parse_line(line)
    return [parsed] if @focused_line
    parsed
  end
end
parse_line(line) click to toggle source
# File lib/tableware/parser.rb, line 43
        def parse_line(line)
  line
    .strip
    .tap { |ln| @focused_line = ln[0] == '>' }
    .sub(ROW_START, '')
    .sub(ROW_END, '')
    .split(' | ')
    .map!(&:strip)
end
prepare_lines(input) click to toggle source
# File lib/tableware/parser.rb, line 29
        def prepare_lines(input)
  lines = input.strip.lines

  @data_start = lines[1] =~ /^\s*[-=+\| ]+\s*$/ ? 2 : 0
  if @data_start.nonzero?
    @headers = parse_line(lines[0])
               .map!(&:downcase)
               .map! { |head| head.gsub(/\s+/, '_') }
               .map!(&:to_sym)
  end

  lines
end