Module: Libis::Tools::Csv
- Defined in:
- lib/libis/tools/csv.rb
Class Method Summary collapse
-
.open(file_name, **options) ⇒ CSV
Open CSV object.
Class Method Details
.open(file_name, **options) ⇒ CSV
Returns Open CSV object.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/libis/tools/csv.rb', line 10 def self.open(file_name, **) = { mode: 'rb:UTF-8', required: %w'', optional: %w'', col_sep: ',', quote_char: '"' }.merge mode = .delete(:mode) required_headers = .delete(:required) optional_headers = .delete(:optional) [:headers] = true [:return_headers] = true csv = ::CSV.open(file_name, mode, **) line = csv.shift found_headers = required_headers & line.headers return csv if found_headers.size == required_headers.size raise RuntimeError, "CSV headers not found: #{required_headers - found_headers}" unless found_headers.empty? csv.close [:headers] = (required_headers + optional_headers)[0...line.size] raise RuntimeError, 'CSV does not contain enough columns' if required_headers.size > line.size [:return_headers] = true csv = ::CSV.open(file_name, mode, **) csv.shift csv end |