Skip to content

Commit

Permalink
Refactor JSON::Schema and fix ListOptionTest.
Browse files Browse the repository at this point in the history
* Refactor JSON::Schema#initialize to move schema URI generation into
  its own method, #generate_schema_uri.
* Refactor JSON::Schema#base_uri to do less path munging itself.
* Fix ListOptionTest, which was relying on seemingly unintended
  behaviour where JSON::Schema's constructor was modifying a URI
  in-place, thus appending a '#' to the URI used in the test. As
  JSON::Schema's constructor doesn't modify its arguments anymore,
  this test started to fail.
  • Loading branch information
gabrielg committed Nov 7, 2014
1 parent ca23261 commit 482521d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 19 deletions.
34 changes: 16 additions & 18 deletions lib/json-schema/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,11 @@

module JSON
class Schema

attr_accessor :schema, :uri, :validator

def initialize(schema,uri,parent_validator=nil)
def initialize(schema, uri, parent_validator = nil)
@schema = self.class.stringify(schema)
@uri = uri

# If there is an ID on this schema, use it to generate the URI
if @schema['id'] && @schema['id'].kind_of?(String)
temp_uri = URI.parse(@schema['id'])
if temp_uri.relative?
uri = uri.merge(@schema['id'])
temp_uri = uri
end
@uri = temp_uri
end
@uri.fragment = ''
@uri = generate_schema_uri(uri)

# If there is a $schema on this schema, use it to determine which validator to use
if @schema['$schema']
Expand Down Expand Up @@ -50,14 +38,24 @@ def self.stringify(schema)
end

def base_uri
parts = @uri.to_s.split('/')
parts.pop
parts.join('/') + '/'
@uri.merge(File.dirname(@uri.path)).to_s
end

def to_s
@schema.to_json
end

private

def generate_schema_uri(uri)
schema_uri = uri.clone
schema_uri.fragment = ''
return schema_uri unless @schema['id'] && @schema['id'].kind_of?(String)

id_uri = URI.parse(@schema['id'])
return id_uri unless id_uri.relative?

schema_uri.merge(id_uri.path)
end
end
end

2 changes: 1 addition & 1 deletion test/test_list_option.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def test_list_option_reusing_schemas
"properties" => { "a" => { "type" => "integer" } }
}

uri = URI.parse('http://example.com/item')
uri = URI.parse('http://example.com/item#')
schema = JSON::Schema.new(schema_hash, uri)
JSON::Validator.add_schema(schema)

Expand Down

0 comments on commit 482521d

Please sign in to comment.