Skip to content

Commit

Permalink
users can provide optional expression cache
Browse files Browse the repository at this point in the history
  • Loading branch information
ggmichaelgo committed Nov 25, 2024
1 parent caaf95b commit 1b36aab
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 4 deletions.
3 changes: 1 addition & 2 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ end
gemspec

gem "base64"
gem "lru_redux"

group :benchmark, :test do
gem 'benchmark-ips'
Expand All @@ -28,5 +29,3 @@ group :test do
gem 'liquid-c', github: 'Shopify/liquid-c', ref: 'main'
end
end

gem "lru_redux"
4 changes: 3 additions & 1 deletion lib/liquid/expression.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ def parse(markup, ss = StringScanner.new(""), cache = nil)

# Cache only exists during parsing
if cache
cache.fetch(markup) { inner_parse(markup, ss, cache).freeze }
return cache[markup] if cache.key?(markup)

cache[markup] = inner_parse(markup, ss, cache).freeze
else
inner_parse(markup, ss, nil).freeze
end
Expand Down
2 changes: 1 addition & 1 deletion lib/liquid/parse_context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def initialize(options = Const::EMPTY_HASH)
# constructing new StringScanner in Lexer, Tokenizer, etc is expensive
# This StringScanner will be shared by all of them
@string_scanner = StringScanner.new("")
@expression_cache = LruRedux::Cache.new(10_000)
@expression_cache = options[:expression_cache] || LruRedux::Cache.new(1000)

self.depth = 0
self.partial = false
Expand Down
22 changes: 22 additions & 0 deletions test/integration/expression_test.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require 'test_helper'
require 'lru_redux'

class ExpressionTest < Minitest::Test
def test_keyword_literals
Expand Down Expand Up @@ -54,6 +55,27 @@ def test_quirky_negative_sign_expression_markup
)
end

def test_expression_cache
skip("Liquid-C does not support Expression caching") if defined?(Liquid::C) && Liquid::C.enabled

cache = LruRedux::Cache.new(10)
template = <<~LIQUID
{% assign x = 1 %}
{{ x }}
{% assign x = 2 %}
{{ x }}
{% assign y = 1 %}
{{ y }}
LIQUID

Liquid::Template.parse(template, expression_cache: cache).render

assert_equal(
["1", "2", "x", "y"],
cache.to_a.map { _1[0] }.sort,
)
end

private

def assert_expression_result(expect, markup, **assigns)
Expand Down

0 comments on commit 1b36aab

Please sign in to comment.