Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Small refactoring: extract validate_enum and validate_const methods #113

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions lib/json_schemer/schema/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ def validate_instance(instance, &block)
return if schema == true || schema.empty?

type = schema['type']
enum = schema['enum']
all_of = schema['allOf']
any_of = schema['anyOf']
one_of = schema['oneOf']
Expand Down Expand Up @@ -122,8 +121,8 @@ def validate_instance(instance, &block)
end
end

yield error(instance, 'enum') if enum && !enum.include?(data)
yield error(instance, 'const') if schema.key?('const') && schema['const'] != data
validate_enum(instance, &block)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should pass enum to this method instead:

validate_enum(instance, enum, &block) if enum

validate_const(instance, &block)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here. And you could pull out const above (similar to enum on line 87):

validate_const(instance, const, &block) if schema.key?('const')


if all_of
all_of.each_with_index do |subschema, index|
Expand Down Expand Up @@ -589,6 +588,20 @@ def validate_object(instance, &block)
end
end

def validate_enum(instance, &block)
enum = instance.schema['enum']
data = instance.data

yield error(instance, 'enum') if enum && !enum.include?(data)
end

def validate_const(instance, &block)
data = instance.data
schema = instance.schema

yield error(instance, 'const') if schema.key?('const') && schema['const'] != data
end

def safe_strict_decode64(data)
Base64.strict_decode64(data)
rescue ArgumentError => e
Expand Down