Sha256: 7097fd3b9283d5f9d6789b21eb86568d4b2e9a6780995d258f4440a571107128

Contents?: true

Size: 1.37 KB

Versions: 12

Compression:

Stored size: 1.37 KB

Contents

# 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

Version data entries

12 entries across 12 versions & 2 rubygems

Version Path
iso-jsonpath-1.1.7 lib/jsonpath/proxy.rb
iso-jsonpath-1.1.6 lib/jsonpath/proxy.rb
jsonpath-1.1.5 lib/jsonpath/proxy.rb
jsonpath-1.1.4 lib/jsonpath/proxy.rb
jsonpath-1.1.3 lib/jsonpath/proxy.rb
jsonpath-1.1.2 lib/jsonpath/proxy.rb
jsonpath-1.1.0 lib/jsonpath/proxy.rb
jsonpath-1.0.7 lib/jsonpath/proxy.rb
jsonpath-1.0.6 lib/jsonpath/proxy.rb
jsonpath-1.0.5 lib/jsonpath/proxy.rb
jsonpath-1.0.4 lib/jsonpath/proxy.rb
jsonpath-1.0.3 lib/jsonpath/proxy.rb