Skip to content

Commit

Permalink
Add deep to compact filter
Browse files Browse the repository at this point in the history
  • Loading branch information
andershagbard committed Oct 16, 2023
1 parent 2800d8d commit 4c45606
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/liquid/standardfilters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,10 @@ def map(input, property, options = {})
# Removes any `nil` items from an array.
# @liquid_syntax array | compact
# @liquid_return [array[untyped]]
def compact(input, property = nil)
# @liquid_optional_param deep [boolean | string] Whether to use dot notation to perform a deep search. A string can be passed to change separator.
def compact(input, property = nil, options = {})
options = {} unless options.is_a?(Hash)
deep = deep_search_properties(property, options)
ary = InputIterator.new(input, context)

if property.nil?
Expand All @@ -539,7 +542,7 @@ def compact(input, property = nil)
[]
else
ary.reject do |item|
item[property].nil?
deep[:enable] ? item.dig(*deep[:properties]).nil? : item[property].nil?
rescue TypeError
raise_property_error(property)
rescue NoMethodError
Expand Down
39 changes: 39 additions & 0 deletions test/integration/standard_filter_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,45 @@ def test_compact_invalid_property
end
end

def test_compact_deep_default_separator
input = [
{ "foo" => { "bar" => "baz", "handle" => "alpha" } },
{ "foo" => { "handle" => "beta" } },
{ "foo" => { "bar" => "qux", "handle" => "charlie" } },
]
expectation = [
{ "foo" => { "bar" => "baz", "handle" => "alpha" } },
{ "foo" => { "bar" => "qux", "handle" => "charlie" } },
]
assert_equal(expectation, @filters.compact(input, "foo.bar", { "deep" => true }))
end

def test_compact_deep_custom_separator
input = [
{ "foo" => { "bar" => "baz", "handle" => "alpha" } },
{ "foo" => { "handle" => "beta" } },
{ "foo" => { "bar" => "qux", "handle" => "charlie" } },
]
expectation = [
{ "foo" => { "bar" => "baz", "handle" => "alpha" } },
{ "foo" => { "bar" => "qux", "handle" => "charlie" } },
]
assert_equal(expectation, @filters.where(input, "foo_bar", "baz", { "deep" => "_" }))
end

def test_compact_deep_off_by_default
input = [
{ "foo.bar" => "baz", "handle" => "alpha" },
{ "foo.handle" => "beta" },
{ "foo.bar" => "qux", "handle" => "charlie" },
]
expectation = [
{ "foo.bar" => "baz", "handle" => "alpha" },
{ "foo.bar" => "qux", "handle" => "charlie" },
]
assert_equal(expectation, @filters.where(input, "foo.bar", "baz"))
end

def test_reverse
assert_equal([4, 3, 2, 1], @filters.reverse([1, 2, 3, 4]))
end
Expand Down

0 comments on commit 4c45606

Please sign in to comment.