File: helpers.rb

package info (click to toggle)
ruby-json-spec 1.1.5-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 312 kB
  • sloc: ruby: 1,059; makefile: 2
file content (62 lines) | stat: -rw-r--r-- 1,525 bytes parent folder | download | duplicates (4)
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
require "multi_json"

module JsonSpec
  module Helpers
    extend self

    def parse_json(json, path = nil)
      ruby = MultiJson.decode("[#{json}]").first
      value_at_json_path(ruby, path)
    rescue MultiJson::DecodeError
      MultiJson.decode(json)
    end

    def normalize_json(json, path = nil)
      ruby = parse_json(json, path)
      generate_normalized_json(ruby)
    end

    def generate_normalized_json(ruby)
      case ruby
      when Hash, Array then JSON.pretty_generate(ruby)
      else ruby.to_json
      end
    end

    def load_json(relative_path)
      missing_json_directory! if JsonSpec.directory.nil?
      path = File.join(JsonSpec.directory, relative_path)
      missing_json_file!(path) unless File.exist?(path)
      File.read(path)
    end

    private
      def value_at_json_path(ruby, path)
        return ruby unless path

        path.split("/").inject(ruby) do |value, key|
          case value
          when Hash
            value.fetch(key){ missing_json_path!(path) }
          when Array
            missing_json_path!(path) unless key =~ /^\d+$/
            value.fetch(key.to_i){ missing_json_path!(path) }
          else
            missing_json_path!(path)
          end
        end
      end

      def missing_json_path!(path)
        raise JsonSpec::MissingPath.new(path)
      end

      def missing_json_directory!
        raise JsonSpec::MissingDirectory
      end

      def missing_json_file!(path)
        raise JsonSpec::MissingFile.new(path)
      end
  end
end