Class: IOStreams::Tabular::Parser::Psv

Inherits:
Base
  • Object
show all
Defined in:
lib/io_streams/tabular/parser/psv.rb

Overview

For parsing a single line of Pipe-separated values

Instance Method Summary collapse

Methods inherited from Base

#requires_header?

Instance Method Details

#parse(row) ⇒ Object

Returns [Array] the parsed PSV line



19
20
21
22
23
24
25
# File 'lib/io_streams/tabular/parser/psv.rb', line 19

def parse(row)
  return row if row.is_a?(::Array)

  raise(IOStreams::Errors::TypeMismatch, "Format is :psv. Invalid input: #{row.class.name}") unless row.is_a?(String)

  row.split("|")
end

#parse_header(row) ⇒ Object

Returns [Array<String>] the header row. Returns nil if the row is blank.



8
9
10
11
12
13
14
15
16
# File 'lib/io_streams/tabular/parser/psv.rb', line 8

def parse_header(row)
  return row if row.is_a?(::Array)

  unless row.is_a?(String)
    raise(IOStreams::Errors::InvalidHeader, "Format is :psv. Invalid input header: #{row.class.name}")
  end

  row.split("|")
end

#render(row, header) ⇒ Object

Return the supplied array as a single line JSON string.



28
29
30
31
32
33
34
# File 'lib/io_streams/tabular/parser/psv.rb', line 28

def render(row, header)
  array          = header.to_array(row)
  cleansed_array = array.collect do |i|
    i.is_a?(String) ? i.tr("|", ":") : i
  end
  cleansed_array.join("|")
end