File: error.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 (85 lines) | stat: -rw-r--r-- 1,792 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
module JsonSchema
  class Error < RuntimeError
  end

  class AggregateError < Error
    attr_accessor :errors

    def initialize(errors)
      @errors = errors
    end

    def to_s
      @errors.join(" ")
    end
  end

  class SchemaError < Error
    attr_accessor :message, :schema, :type

    def self.aggregate(errors)
      errors.map(&:to_s)
    end

    def initialize(schema, message, type)
      @schema = schema
      @message = message
      @type = type
    end

    def to_s
      if schema && schema.pointer
        "#{schema.pointer}: #{message}"
      else
        message
      end
    end
  end

  class ValidationError < SchemaError
    attr_accessor :data, :path, :sub_errors

    def initialize(schema, path, message, type, options = {})
      super(schema, message, type)
      @path = path

      # TODO: change to named optional arguments when Ruby 1.9 support is
      # removed
      @data = options[:data]
      @sub_errors = options[:sub_errors]
    end

    def pointer
      path.join("/")
    end

    def to_s
      "#{pointer}: failed schema #{schema.pointer}: #{message}"
    end
  end

  module ErrorFormatter
    def to_list(list)
      words_connector     = ', '
      two_words_connector = ' or '
      last_word_connector = ', or '

      length = list.length
      joined_list = case length
                    when 1
                      list[0]
                    when 2
                      "#{list[0]}#{two_words_connector}#{list[1]}"
                     else
                      "#{list[0...-1].join(words_connector)}#{last_word_connector}#{list[-1]}"
                    end

      if joined_list[0] =~ /^[aeiou]/
        "an #{joined_list}"
      else
        "a #{joined_list}"
      end
    end
    module_function :to_list
  end
end