Class: Transporter::Service::Validations::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/transporter/service/validations.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Validator

Returns a new instance of Validator.



26
27
28
29
30
# File 'lib/transporter/service/validations.rb', line 26

def initialize(&block)
  @validations = Hash.new {|h,k| h[k] = [] }
  @errors = Hash.new {|h,k| h[k] = [] }
  block.call(self) if block
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



24
25
26
# File 'lib/transporter/service/validations.rb', line 24

def errors
  @errors
end

Instance Method Details

#has_keys(*keys) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/transporter/service/validations.rb', line 32

def has_keys(*keys)
  keys.each do |key|
    @validations[key] << lambda do |config|
      config.has_key?(key) or raise TypeError, "config must include '#{key}', but does not"
    end
  end
end

#key_is_one_of(key, values) ⇒ Object



46
47
48
49
50
# File 'lib/transporter/service/validations.rb', line 46

def key_is_one_of(key, values)
  @validations[key] << lambda do |config|
    values.include? config[key] or raise TypeError, "config '#{key}' must be one of '#{values.join(", ")}'"
  end
end

#key_matches(key, format) ⇒ Object



40
41
42
43
44
# File 'lib/transporter/service/validations.rb', line 40

def key_matches(key, format)
  @validations[key] << lambda do |config|
    config[key] =~ format or raise TypeError, "config '#{key}' must match '#{format}'"
  end
end

#valid?(config) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/transporter/service/validations.rb', line 52

def valid?(config)
  errors.clear

  @validations.each do |key, validation_list|
    validation_list.each do |validation|
      begin
        validation.call(config)
      rescue TypeError => e
        errors[key] << e.message
      end
    end
  end

  errors.empty?
end