lib/csv2hash.rb in csv2hash-0.0.2 vs lib/csv2hash.rb in csv2hash-0.1

- old
+ new

@@ -5,69 +5,83 @@ require 'csv2hash/validator/collection' require 'csv2hash/parser' require 'csv2hash/parser/mapping' require 'csv2hash/parser/collection' require 'csv2hash/csv_array' +require 'csv2hash/data_wrapper' +require 'csv2hash/notifier' +require 'csv2hash/extra_validator' + require 'csv' class Csv2hash - attr_accessor :definition, :file_path, :data, :data_source + attr_accessor :definition, :file_path, :data, :notifier, :exception_mode, :errors, :ignore_blank_line - def initialize definition, file_path, exception=true - @definition, @file_path = definition, file_path - dynamic_parser_loading - @exception, @errors = exception, [] - dynamic_validator_loading + def initialize definition, file_path, exception_mode=true, data_source=nil, ignore_blank_line=false + @data_source = data_source + self.definition, self.file_path = definition, file_path + dynamic_lib_loading 'Parser' + self.exception_mode, self.errors = exception_mode, [] + dynamic_lib_loading 'Validator' + self.notifier = Notifier.new + self.ignore_blank_line = ignore_blank_line + init_plugins end + def init_plugins + begin + @plugins = [] + ::Csv2hash::Plugins.constants.each do |name| + @plugins << ::Csv2hash::Plugins.const_get(name).new(self) + end + rescue; end + end + def parse load_data_source + definition.validate! definition.default! validate_data! - if valid? - fill! - data - else - csv_with_errors + + Csv2hash::DataWrapper.new.tap do |response| + if valid? + fill! + response.data = data[:data] + else + response.valid = false + response.errors = csv_with_errors + notifier.notify response + end end end def csv_with_errors @csv_with_errors ||= begin CsvArray.new.tap do |rows| errors.each do |error| - rows << (([data_source[error[:x]][error[:y]]]||[nil]) + [error[:message]]) + rows << error.merge({ value: (data_source[error[:y]][error[:x]] rescue nil) }) end - end.to_csv + end #.to_csv end end # protected def data_source - @data_source ||= CSV.read @file_path + @data_source ||= CSV.read self.file_path end alias_method :load_data_source, :data_source private - def dynamic_validator_loading + def dynamic_lib_loading type case definition.type - when Definition::MAPPING - self.extend Validator::Mapping - when Definition::COLLECTION - self.extend Validator::Collection - end - end - - def dynamic_parser_loading - case definition.type - when Definition::MAPPING - self.extend Parser::Mapping - when Definition::COLLECTION - self.extend Parser::Collection + when Csv2hash::Definition::MAPPING + self.extend Module.module_eval("Csv2hash::#{type}::Mapping") + when Csv2hash::Definition::COLLECTION + self.extend Module.module_eval("Csv2hash::#{type}::Collection") end end end \ No newline at end of file