1
0
Fork 0
mirror of https://github.com/fog/fog.git synced 2022-11-09 13:51:43 -05:00

Add support for non-strict validations, and nullable arrays/hashes.

This commit is contained in:
Dan Prince 2011-09-28 15:24:40 -04:00
parent a90eb43bd2
commit 20ccb7ca81
2 changed files with 22 additions and 6 deletions

View file

@ -9,6 +9,8 @@ module Fog
module String; end
module Time; end
module Float; end
module Hash; end
module Array; end
end
end
[FalseClass, TrueClass].each {|klass| klass.send(:include, Fog::Boolean)}
@ -17,21 +19,23 @@ end
[NilClass, Time].each {|klass| klass.send(:include, Fog::Nullable::Time)}
[Integer, NilClass].each {|klass| klass.send(:include, Fog::Nullable::Integer)}
[Float, NilClass].each {|klass| klass.send(:include, Fog::Nullable::Float)}
[Hash, NilClass].each {|klass| klass.send(:include, Fog::Nullable::Hash)}
[Array, NilClass].each {|klass| klass.send(:include, Fog::Nullable::Array)}
module Shindo
class Tests
def formats(format)
def formats(format, strict=true)
raise ArgumentError, 'format is nil' unless format
test('has proper format') do
formats_kernel(instance_eval(&Proc.new), format)
formats_kernel(instance_eval(&Proc.new), format, true, strict)
end
end
private
def formats_kernel(original_data, original_format, original = true)
def formats_kernel(original_data, original_format, original = true, strict = true)
valid = true
data = original_data.dup
format = original_format.dup
@ -49,7 +53,7 @@ module Shindo
for element in datum
type = value.first
if type.is_a?(Hash)
valid &&= formats_kernel({:element => element}, {:element => type}, false)
valid &&= formats_kernel({:element => element}, {:element => type}, false, strict)
else
valid &&= element.is_a?(type)
end
@ -57,7 +61,7 @@ module Shindo
end
when Hash
valid &&= datum.is_a?(Hash) || p("#{key.inspect} not Hash: #{datum.inspect}")
valid &&= formats_kernel(datum, value, false)
valid &&= formats_kernel(datum, value, false, strict)
else
p "#{key.inspect} not #{value.inspect}: #{datum.inspect}" unless datum.is_a?(value)
valid &&= datum.is_a?(value)
@ -65,7 +69,11 @@ module Shindo
end
p data unless data.empty?
p format unless format.empty?
valid &&= data.empty? && format.empty?
if strict
valid &&= data.empty? && format.empty?
else
valid &&= format.empty?
end
if !valid && original
@message = "#{original_data.inspect} does not match #{original_format.inspect}"
end

View file

@ -20,6 +20,10 @@ Shindo.tests('test_helper', 'meta') do
formats_kernel([{:a => :b}], [{:a => Symbol}])
end
test('non strict extra data') do
formats_kernel({:a => :b, :b => :c}, {:a => Symbol}, true, false)
end
end
tests('returns false') do
@ -36,6 +40,10 @@ Shindo.tests('test_helper', 'meta') do
!formats_kernel({}, {:a => String})
end
test('non strict extra data') do
!formats_kernel({:a => :b, :b => :c}, {:z => Symbol}, true, false)
end
end
end