Skip to content

Commit d1937e9

Browse files
fix(filter): handle nil argument for replace_last (#177)
When `replace_last` is called with a `nil` value for the string to be replaced, it should append the replacement string to the input. This was not happening, and the filter was returning the input string unchanged. This commit fixes this by checking if the string to be replaced is empty after being converted to a string, and if so, appending the replacement. A doctest and an integration test have been added to cover this case. Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
1 parent 47b0b8a commit d1937e9

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

lib/solid/standard_filter.ex

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -705,25 +705,31 @@ defmodule Solid.StandardFilter do
705705
"foo"
706706
iex> Solid.StandardFilter.replace_last("foo", "f", "b")
707707
"boo"
708+
iex> Solid.StandardFilter.replace_last("Take my protein", nil, "#")
709+
"Take my protein#"
708710
"""
709711
@spec replace_last(String.t(), String.t(), String.t()) :: String.t()
710712
def replace_last(input, string, replacement) do
711713
input = to_str(input)
712-
string = to_str(string)
714+
string_arg = to_str(string)
713715
replacement = to_str(replacement)
714716

715-
case last_index(input, string) do
717+
case last_index(input, string_arg) do
716718
nil ->
717-
input
719+
if string_arg == "" do
720+
input <> replacement
721+
else
722+
input
723+
end
718724

719725
index ->
720726
prefix = :binary.part(input, 0, index)
721727

722728
suffix =
723729
:binary.part(
724730
input,
725-
index + byte_size(string),
726-
byte_size(input) - (index + byte_size(string))
731+
index + byte_size(string_arg),
732+
byte_size(input) - (index + byte_size(string_arg))
727733
)
728734

729735
prefix <> replacement <> suffix

test/solid/integration/scenarios/filter/input.liquid

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,7 @@ base64
460460
{{ "hello" | replace_last: "ll" }}
461461
{{ "hello" | replace_last: "l", "p" }}
462462
{{ "abab" | replace_last: "a", "c" }}
463+
{{ "Take my protein" | replace_last: nosuchthing, "#" }}
463464

464465
default
465466

0 commit comments

Comments
 (0)