Sha256: ef10884089ff0a38ee7064624c1f0f094acea3295e33f03060365f32cdfea458

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

# frozen_string_literal: true

module ActiveFields
  module Validators
    # Validates the active_value value
    class BaseValidator
      attr_reader :active_field, :errors

      def initialize(active_field)
        @active_field = active_field
        @errors = Set.new
      end

      def validate(value)
        perform_validation(value)
        valid?
      end

      def valid?
        errors.empty?
      end

      private

      def perform_validation(value)
        raise NotImplementedError
      end

      def validate_size(value, min:, max:)
        if min && value.size < min
          errors << [:size_too_short, count: min]
        end

        if max && value.size > max
          errors << [:size_too_long, count: max]
        end
      end

      def validate_length(value, min:, max:)
        if min && value.length < min
          errors << [:too_short, count: min]
        end

        if max && value.length > max
          errors << [:too_long, count: max]
        end
      end

      def validate_minmax(value, min:, max:)
        # maybe acts_like?(:date) || acts_like?(:time)
        if min && value < min
          formatted =
            if min.respond_to?(:strftime) && defined?(I18n) && I18n.respond_to?(:l)
              I18n.l(min)
            else
              min
            end
          errors << [:greater_than_or_equal_to, count: formatted]
        end

        if max && value > max
          formatted =
            if max.respond_to?(:strftime) && defined?(I18n) && I18n.respond_to?(:l)
              I18n.l(max)
            else
              max
            end
          errors << [:less_than_or_equal_to, count: formatted]
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_fields-0.2.0 lib/active_fields/validators/base_validator.rb