Sha256: 1382756b43d78b612e93d6301befbd19f98fcfd1d5c3b2befdd950c6f11e0a68
Contents?: true
Size: 1.59 KB
Versions: 2
Compression:
Stored size: 1.59 KB
Contents
require 'csv' module Valigator module CSV class Validator attr_reader :filename, :errors def initialize(filename) @filename = filename @errors = [] end def validate(options = {}) ::CSV.foreach(@filename, csv_options(options)) do |row| validate_fields row, options end rescue ::CSV::MalformedCSVError, ArgumentError => error raise if unrelated_error?(error) @errors << CSV::Error.new(error) end private def csv_options(options = {}) { col_sep: options[:col_sep] || ',', quote_char: options[:quote_char] || '"', encoding: options[:encoding] || 'UTF-8', headers: options[:headers] || false, return_headers: options[:return_headers] || false } end def unrelated_error?(error) error.is_a?(ArgumentError) && error.message != 'invalid byte sequence in UTF-8' end def validate_fields(row, options={}) return unless options[:fields] && options[:field_validators] options[:fields].each_with_index do |field, index| field_validator = options[:field_validators][field] if field_validator and !field_validator.valid?(row[index]) add_field_error(field, field_validator) end end end def add_field_error(field, validator) @errors << CSV::Error.new({ type: validator.error_type, message: validator.error_message, row: $INPUT_LINE_NUMBER, field: field }) end end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
valigator-csv-1.3.1 | lib/valigator/csv/validator.rb |
valigator-csv-1.3.0 | lib/valigator/csv/validator.rb |