Class: JsonDataExtractor::PathCompiler::JsonPathWrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/json_data_extractor/path_compiler.rb

Overview

Wrapper for JsonPath that caches serialization

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ JsonPathWrapper

Returns a new instance of JsonPathWrapper.



19
20
21
22
23
# File 'lib/json_data_extractor/path_compiler.rb', line 19

def initialize(path)
  @json_path = JsonPath.new(path)
  @cached_json = nil
  @cached_data_id = nil
end

Instance Method Details

#on(data) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/json_data_extractor/path_compiler.rb', line 25

def on(data)
  # Cache the JSON serialization if we're processing the same data object
  data_id = data.object_id
  
  if data.is_a?(String)
    @json_path.on(data)
  else
    # Only serialize once per data object
    if @cached_data_id != data_id
      @cached_json = Oj.dump(data, mode: :compat)
      @cached_data_id = data_id
    end
    @json_path.on(@cached_json)
  end
end