Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/jmespath.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ module JMESPath
require 'jmespath/nodes'
require 'jmespath/parser'
require 'jmespath/runtime'
require 'jmespath/caching_runtime'
require 'jmespath/token'
require 'jmespath/token_stream'
require 'jmespath/util'
Expand All @@ -28,12 +29,15 @@ def search(expression, data, runtime_options = {})
when IO, StringIO then JSON.parse(data.read)
else data
end
Runtime.new(runtime_options).search(expression, data)
runtime = runtime_options.empty? ? DEFAULT_RUNTIME : Runtime.new(runtime_options)
runtime.search(expression, data)
end

# @api private
def load_json(path)
JSON.parse(File.open(path, 'r', encoding: 'UTF-8', &:read))
end
end

DEFAULT_RUNTIME = CachingRuntime.new
end
30 changes: 30 additions & 0 deletions lib/jmespath/caching_runtime.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# frozen_string_literal: true
require 'thread'

module JMESPath
# @api private
class CachingRuntime < Runtime
def initialize(options = {})
super(options.merge(cache_expressions: false))
@mutex = Mutex.new
@cache = {}
end

def search(expression, data)
if cached = @cache[expression]
cached.visit(data)
else
cache_expression(expression).visit(data)
end
end

private

def cache_expression(expression)
@mutex.synchronize do
@cache.clear if @cache.size > 1000
@cache[expression] ||= @parser.parse(expression).optimize
end
end
end
end