Module: CFoundry::Validator

Defined in:
lib/cfoundry/validator.rb

Class Method Summary collapse

Class Method Details

.validate_type(val, type) ⇒ Object



34
35
36
37
38
# File 'lib/cfoundry/validator.rb', line 34

def validate_type(val, type)
  unless value_matches?(val, type)
    raise CFoundry::Mismatch.new(type, val)
  end
end

.value_matches?(val, type) ⇒ Boolean

Returns:

  • (Boolean)


4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/cfoundry/validator.rb', line 4

def value_matches?(val, type)
  return true if val.nil?

  case type
  when Class
    val.is_a?(type)
  when Regexp
    val.is_a?(String) && !!(val =~ type)
  when :url
    value_matches?(val, URI::regexp(%w(http https)))
  when :https_url
    value_matches?(val, URI::regexp("https"))
  when :boolean
    val.is_a?(TrueClass) || val.is_a?(FalseClass)
  when Array
    val.all? do |x|
      value_matches?(x, type.first)
    end
  when Hash
    val.is_a?(Hash) &&
      type.all? { |name, subtype|
        val.key?(name) && value_matches?(val[name], subtype)
      }
  when nil
    true
  else
    val.is_a?(Object.const_get(type.to_s.capitalize))
  end
end