Skip to content

Instantly share code, notes, and snippets.

@burke
Last active September 24, 2021 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burke/edd2e5f65ce8b9afc99d17903f9f697c to your computer and use it in GitHub Desktop.
Save burke/edd2e5f65ce8b9afc99d17903f9f697c to your computer and use it in GitHub Desktop.
class JSONTypeClass < T::Types::Base
ScalarType = T.type_alias { T.any(String, Numeric, NilClass, FalseClass, TrueClass) }
IterType = T.type_alias { T.any(ScalarType, T::Array[T.untyped], T::Hash[String, T.untyped]) }
def name
'JSON'
end
def valid?(obj)
# in this particular case I don't think it makes sense to distinguish
recursively_valid?(obj)
end
def recursively_valid?(obj)
return false unless IterType.recursively_valid?(obj)
case obj
when Hash
obj.all? { |_, v| recursively_valid?(v) }
when Array
obj.all? { |e| recursively_valid?(e) }
else
true
end
end
def validate!(obj)
IterType.validate!(obj)
case obj
when Hash
obj.all? { |_, v| validate!(v) }
when Array
obj.all? { |e| validate!(e) }
end
end
end
JSONType = JSONTypeClass.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment