lib/csv2hash/validator.rb in csv2hash-0.0.1 vs lib/csv2hash/validator.rb in csv2hash-0.0.2
- old
+ new
@@ -1,34 +1,42 @@
module Validator
-
- def validate_data!
+
+ attr_accessor :errors, :exception
+
+ def validate_rules y=nil
definition.rules.each do |rule|
- if (rule.fetch(:maptype) == 'cell')
- x, y = rule.fetch :position
- validate_rule x, y, rule
+ _y, x = position rule.fetch(:position)
+ begin
+ validate_cell (_y||y), x, rule
+ rescue => e
+ errors << { y: (_y||y), x: x, message: e.message, key: rule.fetch(:key) }
+ raise if exception
end
end
end
- private
+ def valid?() errors.empty?; end
- def validate_rule x, y, rule
+ protected
+
+ def validate_cell y, x, rule
+
+ value = data_source[y][x] rescue nil
+
begin
- raise unless data_source[x]
- unless rule.fetch :allow_blank
- raise unless data_source[x][y]
+ raise unless value unless rule.fetch :allow_blank
+ if value && (values = rule.fetch :values)
+ raise unless values.include?(value)
end
- if (values = rule.fetch :values)
- raise unless values.include?(data_source[x][y])
- end
rescue => e
- raise message(rule)
+ raise message(rule, y, x)
end
end
- def message rule
- rule.fetch(:message).tap do |msg|
- rule.each { |key, value| msg.gsub! ":#{key.to_s}", value.to_s }
+ def message rule, y, x
+ msg = rule.fetch(:message).tap do |msg|
+ rule.each { |key, value| msg.gsub!(":#{key.to_s}", value.to_s) unless key == :position }
end
+ msg.gsub ':position', "[#{y}, #{x}]"
end
-
+
end
\ No newline at end of file