Skip to content

Commit

Permalink
Fix render cache
Browse files Browse the repository at this point in the history
  • Loading branch information
edgurgel committed Sep 6, 2023
1 parent 307d963 commit 3d8ca32
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 14 deletions.
4 changes: 2 additions & 2 deletions lib/solid/caching.ex
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
defmodule Solid.Caching do
@callback get(key :: term) :: {:ok, Template.t()} | {:error, :not_found}
@callback get(key :: term) :: {:ok, Solid.Template.t()} | {:error, :not_found}

@callback put(key :: term, Template.t()) :: :ok | {:error, term}
@callback put(key :: term, Solid.Template.t()) :: :ok | {:error, term}
end
17 changes: 6 additions & 11 deletions lib/solid/tag/render.ex
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,16 @@ defmodule Solid.Tag.Render do

cache_key = :md5 |> :crypto.hash(template_str) |> Base.encode16(case: :lower)

template =
result =
case apply(cache_module, :get, [cache_key]) do
{:ok, cached_template} ->
cached_template
{:ok, cached_template}

{:error, :not_found} ->
parse_and_cache_partial(template_str, options, cache_key, cache_module)
end

case template do
case result do
{:ok, template} ->
case Solid.render(template, binding_vars, options) do
{:ok, rendered_text} ->
Expand All @@ -81,14 +81,9 @@ defmodule Solid.Tag.Render do
end

defp parse_and_cache_partial(template_str, options, cache_key, cache_module) do
case Solid.parse(template_str, options) do
{:ok, template} = v ->
apply(cache_module, :put, [cache_key, template])

v

{:error, _exception} = v ->
v
with {:ok, template} <- Solid.parse(template_str, options) do
apply(cache_module, :put, [cache_key, template])
{:ok, template}
end
end
end
11 changes: 10 additions & 1 deletion test/solid/tag/render_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ defmodule Solid.Tag.RenderTest do

@impl true
def get(cache_key) do
Agent.get(__MODULE__, &Map.get(&1, cache_key, {:error, :not_found}))
case Agent.get(__MODULE__, &Map.get(&1, cache_key, {:error, :not_found})) do
{:error, :not_found} -> {:error, :not_found}
value -> {:ok, value}
end
end

def get_all() do
Expand Down Expand Up @@ -66,6 +69,12 @@ defmodule Solid.Tag.RenderTest do

assert %{calculated_cache_key => %Solid.Template{parsed_template: [text: ["hello there"]]}} ==
TestCache.get_all()

assert {[text: [["hello there"]]], %Context{}} ==
Render.render(parsed, %Context{},
cache_module: TestCache,
file_system: {Test.SolidFileSystem, nil}
)
end

test "must correctly return error from parsing" do
Expand Down

0 comments on commit 3d8ca32

Please sign in to comment.