Class: Tabulard::Adapters::Csv

Inherits:
Object
  • Object
show all
Includes:
Table
Defined in:
lib/tabulard/adapters/csv.rb

Defined Under Namespace

Classes: InvalidCSV

Constant Summary

Constants included from Table

Table::COL_CONVERTER, Table::Message

Instance Attribute Summary

Attributes included from Table

#messenger

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Table

#close, #closed?, col2int, int2col

Constructor Details

#initialize(io, row_sep: self.class.defaults[:row_sep], col_sep: self.class.defaults[:col_sep], quote_char: self.class.defaults[:quote_char], headers: nil, **opts) ⇒ Csv

Returns a new instance of Csv.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/tabulard/adapters/csv.rb', line 33

def initialize(
  io,
  row_sep: self.class.defaults[:row_sep],
  col_sep: self.class.defaults[:col_sep],
  quote_char: self.class.defaults[:quote_char],
  headers: nil,
  **opts
)
  super(**opts)

  csv = CSV.new(
    io,
    row_sep: row_sep,
    col_sep: col_sep,
    quote_char: quote_char
  )

  if headers
    init_with_headers(csv, headers)
  else
    init_without_headers(csv)
  end
end

Class Method Details

.defaultsObject



29
30
31
# File 'lib/tabulard/adapters/csv.rb', line 29

def self.defaults
  DEFAULTS
end

Instance Method Details

#each_headerObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/tabulard/adapters/csv.rb', line 57

def each_header
  raise_if_closed

  return to_enum(:each_header) { @cols_count } unless block_given?
  return self if @cols_count.zero?

  @headers.each_with_index do |header, col_idx|
    col = Table.int2col(col_idx + 1)

    yield Header.new(col: col, value: header)
  end

  self
end

#each_rowObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/tabulard/adapters/csv.rb', line 72

def each_row
  raise_if_closed

  return to_enum(:each_row) unless block_given?
  return self unless @csv

  handle_malformed_csv do
    @csv.each.with_index(@first_row_name) do |raw, row|
      value = Array.new(@cols_count) do |col_idx|
        col = Table.int2col(col_idx + 1)

        Cell.new(row: row, col: col, value: raw[col_idx])
      end

      yield Row.new(row: row, value: value)
    end
  end

  self
end