File: json_reference.rb

package info (click to toggle)
ruby-brandur-json-schema 0.19.1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 376 kB
  • sloc: ruby: 3,764; makefile: 6
file content (58 lines) | stat: -rw-r--r-- 1,193 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
require "uri"
require_relative "json_pointer"

module JsonReference
  def self.reference(ref)
    Reference.new(ref)
  end

  class Reference
    include Comparable

    attr_accessor :pointer
    attr_accessor :uri

    def initialize(ref)
      # Note that the #to_s of `nil` is an empty string.
      @uri = nil

      # given a simple fragment without '#', resolve as a JSON Pointer only as
      # per spec
      if ref.include?("#")
        uri, @pointer = ref.split('#')
        if uri && !uri.empty?
          @uri = URI.parse(uri)
        end
        @pointer ||= ""
      else
        @pointer = ref
      end

      # normalize pointers by prepending "#" and stripping trailing "/"
      @pointer = "#" + @pointer
      @pointer = @pointer.chomp("/")
    end

    def <=>(other)
      to_s <=> other.to_s
    end

    def inspect
      "\#<JsonReference::Reference #{to_s}>"
    end

    # Given the document addressed by #uri, resolves the JSON Pointer part of
    # the reference.
    def resolve_pointer(data)
      JsonPointer.evaluate(data, @pointer)
    end

    def to_s
      if @uri
        "#{@uri.to_s}#{@pointer}"
      else
        @pointer
      end
    end
  end
end