Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an optional limit argument to split filter #1801

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
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
10 changes: 6 additions & 4 deletions lib/liquid/standardfilters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -284,11 +284,13 @@ def truncatewords(input, words = 15, truncate_string = "...")
# @liquid_type filter
# @liquid_category string
# @liquid_summary
# Splits a string into an array of substrings based on a given separator.
# @liquid_syntax string | split: string
# Splits a string into an array of substrings based on a given separator and an optional limit number
# @liquid_syntax string | split: string, integer
# @liquid_return [array[string]]
def split(input, pattern)
input.to_s.split(pattern.to_s)
def split(input, pattern, limit = 0)
limit = Utils.to_integer(limit)

input.to_s.split(pattern.to_s, limit)
end

# @liquid_public_docs
Expand Down
6 changes: 6 additions & 0 deletions test/integration/standard_filter_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,12 @@ def test_split
assert_equal(['A?Z'], @filters.split('A?Z', '~'))
assert_equal([], @filters.split(nil, ' '))
assert_equal(['A', 'Z'], @filters.split('A1Z', 1))
assert_equal(['a', 'b', 'c,d,e'], @filters.split('a,b,c,d,e', ',', 3))

nil_limit_exception = assert_raises(Liquid::ArgumentError) do
@filters.split('a,b,c,d,e', ',', nil)
end
assert_equal('Liquid error: invalid integer', nil_limit_exception.message)
end

def test_escape
Expand Down
Loading