Class: Sheetah::Backends::Csv

Inherits:
Object
  • Object
show all
Includes:
Sheet
Defined in:
lib/sheetah/backends/csv.rb

Defined Under Namespace

Classes: InvalidCSVError

Constant Summary

Constants included from Sheet

Sheet::COL_CONVERTER

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Sheet

col2int, included, 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]) ⇒ Csv

Returns a new instance of Csv.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/sheetah/backends/csv.rb', line 27

def initialize(
  io,
  row_sep: self.class.defaults[:row_sep],
  col_sep: self.class.defaults[:col_sep],
  quote_char: self.class.defaults[:quote_char]
)
  @csv = CSV.new(
    io,
    row_sep: row_sep,
    col_sep: col_sep,
    quote_char: quote_char
  )

  @headers = detect_headers(@csv)
  @cols_count = @headers.size
end

Class Method Details

.defaultsObject



23
24
25
# File 'lib/sheetah/backends/csv.rb', line 23

def self.defaults
  DEFAULTS
end

Instance Method Details

#closeObject



74
75
76
77
# File 'lib/sheetah/backends/csv.rb', line 74

def close
  # Do nothing: this backend isn't responsible for opening the IO, and therefore it is not
  # responsible for closing it either.
end

#each_headerObject



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/sheetah/backends/csv.rb', line 44

def each_header
  return to_enum(:each_header) { @cols_count } unless block_given?

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

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

  self
end

#each_rowObject



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/sheetah/backends/csv.rb', line 56

def each_row
  return to_enum(:each_row) unless block_given?

  handle_malformed_csv do
    @csv.each.with_index(1) do |raw, row|
      value = Array.new(@cols_count) do |col_idx|
        col = Sheet.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