File: proxy.rb

package info (click to toggle)
ruby-jsonpath 1.1.5-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 332 kB
  • sloc: ruby: 1,831; makefile: 4
file content (67 lines) | stat: -rw-r--r-- 1,404 bytes parent folder | download | duplicates (3)
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
# frozen_string_literal: true

class JsonPath
  class Proxy
    attr_reader :obj
    alias to_hash obj

    def initialize(obj)
      @obj = obj
    end

    def gsub(path, replacement = nil, &replacement_block)
      _gsub(_deep_copy, path, replacement ? proc(&method(:replacement)) : replacement_block)
    end

    def gsub!(path, replacement = nil, &replacement_block)
      _gsub(@obj, path, replacement ? proc(&method(:replacement)) : replacement_block)
    end

    def delete(path = JsonPath::PATH_ALL)
      _delete(_deep_copy, path)
    end

    def delete!(path = JsonPath::PATH_ALL)
      _delete(@obj, path)
    end

    def compact(path = JsonPath::PATH_ALL)
      _compact(_deep_copy, path)
    end

    def compact!(path = JsonPath::PATH_ALL)
      _compact(@obj, path)
    end

    private

    def _deep_copy
      Marshal.load(Marshal.dump(@obj))
    end

    def _gsub(obj, path, replacement)
      JsonPath.new(path)[obj, :substitute].each(&replacement)
      Proxy.new(obj)
    end

    def _delete(obj, path)
      JsonPath.new(path)[obj, :delete].each
      obj = _remove(obj)
      Proxy.new(obj)
    end

    def _remove(obj)
      obj.each do |o|
        if o.is_a?(Hash) || o.is_a?(Array)
          _remove(o)
          o.delete({})
        end
      end
    end

    def _compact(obj, path)
      JsonPath.new(path)[obj, :compact].each
      Proxy.new(obj)
    end
  end
end