Class: Csvtool::Infrastructure::CSV::CsvStatsScanner
- Inherits:
-
Object
- Object
- Csvtool::Infrastructure::CSV::CsvStatsScanner
- Defined in:
- lib/csvtool/infrastructure/csv/csv_stats_scanner.rb
Instance Method Summary collapse
- #call(file_path:, col_sep:, headers_present:) ⇒ Object
-
#initialize(csv: ::CSV) ⇒ CsvStatsScanner
constructor
A new instance of CsvStatsScanner.
Constructor Details
#initialize(csv: ::CSV) ⇒ CsvStatsScanner
Returns a new instance of CsvStatsScanner.
9 10 11 |
# File 'lib/csvtool/infrastructure/csv/csv_stats_scanner.rb', line 9 def initialize(csv: ::CSV) @csv = csv end |
Instance Method Details
#call(file_path:, col_sep:, headers_present:) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/csvtool/infrastructure/csv/csv_stats_scanner.rb', line 13 def call(file_path:, col_sep:, headers_present:) data_row_count = 0 headers = nil column_count = 0 column_stats = [] # Streaming scan: memory grows with per-column metrics, not row count. @csv.foreach(file_path, headers: headers_present, col_sep: col_sep) do |row| if headers_present headers ||= row.headers column_count = headers.length if column_stats.empty? column_stats = headers.map { |name| { name: name, blank_count: 0, non_blank_count: 0 } } end fields = row.fields fields.fill(nil, fields.length...column_count) fields.each_with_index { |value, index| apply_value(column_stats[index], value) } data_row_count += 1 else fields = row.is_a?(::CSV::Row) ? row.fields : row column_count = [column_count, fields.length].max while column_stats.length < column_count column_stats << { name: "column_#{column_stats.length + 1}", blank_count: 0, non_blank_count: 0 } end fields.fill(nil, fields.length...column_count) fields.each_with_index { |value, index| apply_value(column_stats[index], value) } data_row_count += 1 end end { row_count: data_row_count, column_count: column_count, headers: headers, column_stats: column_stats } end |