Skip to content

Commit

Permalink
Add :fragment option and initial test
Browse files Browse the repository at this point in the history
  • Loading branch information
hoxworth committed Jul 3, 2013
1 parent 8c2d7ed commit 3b61193
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
31 changes: 31 additions & 0 deletions lib/json-schema/validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,39 @@ def initialize(schema_data, data, opts={})
@@mutex.synchronize { @base_schema = initialize_schema(schema_data) }
@data = initialize_data(data)
@@mutex.synchronize { build_schemas(@base_schema) }

# If the :fragment option is set, try and validate against the fragment
if opts[:fragment]
@base_schema = schema_from_fragment(@base_schema, opts[:fragment])
end
end

def schema_from_fragment(base_schema, fragment)
fragments = fragment.split("/")

# ensure the first element was a hash, per the fragment spec
if fragments.shift != "#"
raise JSON::Schema::SchemaError.new("Invalid fragment syntax in :fragment option")
end

fragments.each do |f|
if base_schema.is_a?(Hash)
if !base_schema.has_key?(f)
raise JSON::Schema::SchemaError.new("Invalid fragment resolution for :fragment option")
end
base_schema = base_schema[f]
elsif base_schema.is_a?(Array)
if base_schema[f.to_i].nil?
raise JSON::Schema::SchemaError.new("Invalid fragment resolution for :fragment option")
end
base_schema = base_schema[f.to_i]
else
raise JSON::Schema::SchemaError.new("Invalid schema encountered when resolving :fragment option")
end
end

base_schema
end

# Run a simple true/false validation of data against a schema
def validate()
Expand Down
21 changes: 21 additions & 0 deletions test/schemas/test_fragment_resolution.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
require 'test/unit'

class FragmentResolution < Test::Unit::TestCase
def test_fragment_resolution
schema = {
"$schema" => "http://json-schema.org/draft-04/schema#",
"properties" => {
"a" => {
"type" => "object",
"properties" => {
"b" => {"type" => "integer" }
}
}
}
}

data = {"b" => 5}
assert(!JSON::Validator.validate(schema,data))
assert(JSON::Validator.validate(schema,data,:fragment => "#/properties/a"))
end
end

0 comments on commit 3b61193

Please sign in to comment.