lib/lotus/validations/attribute.rb in lotus-validations-0.2.3 vs lib/lotus/validations/attribute.rb in lotus-validations-0.2.4

- old
+ new

@@ -32,24 +32,34 @@ # @param value [Object,nil] the value coming from the input # @param validations [Hash] a set of validation rules # # @since 0.2.0 # @api private - def initialize(attributes, name, value, validations) + def initialize(attributes, name, value, validations, errors) @attributes = attributes @name = name @value = value @validations = validations - @errors = [] + @errors = errors end # @api private # @since 0.2.0 def validate - _with_cleared_errors do - _run_validations - end + presence + acceptance + + return if skip? + + format + inclusion + exclusion + size + confirmation + nested + + @errors end # @api private # @since 0.2.0 attr_reader :value @@ -181,10 +191,25 @@ raise ArgumentError.new("Size validator must be a number or a range, it was: #{ validator }") end end end + # Validates nested Lotus Validations objects + # + # @since 0.2.4 + # @api private + def nested + _validate(__method__) do |validator| + errors = value.validate + errors.each do |error| + new_error = Error.new(error.attribute, error.validation, error.expected, error.actual, @name) + @errors.add new_error.attribute, new_error + end + true + end + end + # @since 0.1.0 # @api private def skip? @value.nil? end @@ -197,35 +222,10 @@ # @api private def blank_value? BlankValueChecker.new(@value).blank_value? end - # Run the defined validations - # - # @since 0.2.0 - # @api private - def _run_validations - presence - acceptance - - return if skip? - - format - inclusion - exclusion - size - confirmation - end - - # @api private - # @since 0.2.0 - def _with_cleared_errors - @errors.clear - yield - @errors.dup.tap {|_| @errors.clear } - end - # Reads an attribute from the validator. # # @since 0.2.0 # @api private def _attribute(name = @name) @@ -236,10 +236,10 @@ # # @since 0.2.0 # @api private def _validate(validation) if (validator = @validations[validation]) && !(yield validator) - @errors.push(Error.new(@name, validation, @validations.fetch(validation), @value)) + @errors.add(@name, Error.new(@name, validation, @validations.fetch(validation), @value)) end end end end end