Sha256: 0ca04b993f8e773d7b83544aab239f5b9297eb23e7a0730e899a8211a32e510c

Contents?: true

Size: 1.19 KB

Versions: 3

Compression:

Stored size: 1.19 KB

Contents

module WeakParameters
  class BaseValidator
    attr_reader :params, :key, :options

    def initialize(params, key, options = {})
      @params = params
      @key = key
      @options = options
    end

    def validate
      raise_error unless valid?
    end

    def required?
      !!options[:required]
    end

    def type
      self.class.name.split("::").last.sub(/Validator$/, "").underscore.to_sym
    end

    private

    def valid?
      case
      when required? && nil?
        false
      when exist? && invalid_type?
        false
      when exist? && exceptional?
        false
      else
        true
      end
    end

    def nil?
      value.nil?
    end

    def exist?
      !nil?
    end

    def exceptional?
      case
      when options[:only].try(:exclude?, value)
        true
      when options[:except].try(:include?, value)
        true
      else
        false
      end
    end

    def value
      params[key]
    end

    def raise_error
      raise WeakParameters::ValidationError, error_message
    end

    def error_message
      "params[#{key.inspect}] is required"
    end

    def valid_type?
      true
    end

    def invalid_type?
      !valid_type?
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
weak_parameters-0.0.7 lib/weak_parameters/base_validator.rb
weak_parameters-0.0.6 lib/weak_parameters/base_validator.rb
weak_parameters-0.0.5 lib/weak_parameters/base_validator.rb