Module: Compel::Validation

Extended by:
Validation
Included in:
Validation
Defined in:
lib/compel/validation/result.rb,
lib/compel/validation/validation.rb,
lib/compel/validation/conditions/if.rb,
lib/compel/validation/conditions/in.rb,
lib/compel/validation/conditions/is.rb,
lib/compel/validation/conditions/max.rb,
lib/compel/validation/conditions/min.rb,
lib/compel/validation/conditions/format.rb,
lib/compel/validation/conditions/length.rb,
lib/compel/validation/conditions/condition.rb,
lib/compel/validation/conditions/max_length.rb,
lib/compel/validation/conditions/min_length.rb

Defined Under Namespace

Classes: Condition, CustomValidator, Format, If, In, Is, Length, Max, MaxLength, Min, MinLength, Range, Result

Constant Summary collapse

CONDITIONS =
{
  is: Validation::Is,
  in: Validation::In,
  min: Validation::Min,
  max: Validation::Max,
  range: Validation::Range,
  format: Validation::Format,
  length: Validation::Length,
  min_length: Validation::MinLength,
  max_length: Validation::MaxLength,
  if: Validation::If,
}

Instance Method Summary collapse

Instance Method Details

#condition_exists?(option_name) ⇒ Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/compel/validation/validation.rb', line 56

def condition_exists?(option_name)
  CONDITIONS.keys.include?(option_name.to_sym)
end

#condition_klass(option_name) ⇒ Object



60
61
62
# File 'lib/compel/validation/validation.rb', line 60

def condition_klass(option_name)
  CONDITIONS[option_name.to_sym]
end

#validate(value, type, options) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/compel/validation/validation.rb', line 31

def validate(value, type, options)
  if value.nil? && !!(options[:required] && options[:required][:value])
    return [options[:required][:message] || 'is required']
  end

  errors = Errors.new

  options.each do |name, option_values|
    next unless condition_exists?(name)

    cloned_options = option_values.dup

    option_value = cloned_options.delete(:value)

    result = condition_klass(name).validate \
      value, option_value, cloned_options.merge(type: type)

    unless result.valid?
      errors.add :base, result.error_message
    end
  end

  errors.to_hash[:base] || []
end