Class: Schema::CSVParser
- Inherits:
-
Object
- Object
- Schema::CSVParser
- Includes:
- Enumerable
- Defined in:
- lib/schema/csv_parser.rb
Overview
Schema::CSVParser is used to create schema models from a csv
Instance Method Summary collapse
- #each ⇒ Object
- #get_mapped_headers(mapped_headers) ⇒ Object
-
#initialize(csv, schema_class, headers = nil) ⇒ CSVParser
constructor
A new instance of CSVParser.
- #missing_fields(required_fields) ⇒ Object (also: #missing_headers)
- #shift ⇒ Object
Constructor Details
#initialize(csv, schema_class, headers = nil) ⇒ CSVParser
Returns a new instance of CSVParser.
8 9 10 11 12 13 14 |
# File 'lib/schema/csv_parser.rb', line 8 def initialize(csv, schema_class, headers = nil) @csv = csv @schema_class = schema_class @headers = (headers || csv.shift) || [] @headers = @headers.map(&:strip) @mapped_headers = schema_class.map_headers_to_attributes(@headers) end |
Instance Method Details
#each ⇒ Object
27 28 29 30 31 |
# File 'lib/schema/csv_parser.rb', line 27 def each while (schema = shift) yield schema end end |
#get_mapped_headers(mapped_headers) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/schema/csv_parser.rb', line 33 def get_mapped_headers(mapped_headers) indexed_headers = [] mapped_headers.each do |_, info| if (index = info[:index]) indexed_headers << @headers[index] elsif (indexes = info[:indexes]) indexed_headers += indexes.map { |i| @headers[i] } else indexed_headers += get_mapped_headers(info) end end indexed_headers end |
#missing_fields(required_fields) ⇒ Object Also known as: missing_headers
16 17 18 |
# File 'lib/schema/csv_parser.rb', line 16 def missing_fields(required_fields) required_fields - get_mapped_headers(@mapped_headers) end |
#shift ⇒ Object
21 22 23 24 25 |
# File 'lib/schema/csv_parser.rb', line 21 def shift return unless (row = @csv.shift) @schema_class.from_array(row, @mapped_headers) end |