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
- #shift ⇒ Object
Constructor Details
#initialize(csv, schema_class, headers = nil) ⇒ CSVParser
Returns a new instance of CSVParser.
8 9 10 11 12 13 |
# 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).map(&:strip) @mapped_headers = schema_class.map_headers_to_attributes(@headers) end |
Instance Method Details
#each ⇒ Object
25 26 27 28 29 |
# File 'lib/schema/csv_parser.rb', line 25 def each while (schema = shift) yield schema end end |
#get_mapped_headers(mapped_headers) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/schema/csv_parser.rb', line 31 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
15 16 17 |
# File 'lib/schema/csv_parser.rb', line 15 def missing_fields(required_fields) required_fields - get_mapped_headers(@mapped_headers) end |
#shift ⇒ Object
19 20 21 22 23 |
# File 'lib/schema/csv_parser.rb', line 19 def shift return unless (row = @csv.shift) @schema_class.from_array(row, @mapped_headers) end |