Implement a pop_item filter

This is just a proxy for Array#pop in Ruby. We're using nil as a
indicator that a number was not passed. If we use 1 as the default,
Array#pop always returns an array. If the number `1` is passed in, then
we just let Array#pop always return an array.
This commit is contained in:
Matt Rogers
2019-08-03 09:38:41 -05:00
parent a87ca206da
commit bd10b0ce76
2 changed files with 31 additions and 0 deletions

View File

@@ -257,6 +257,17 @@ module Jekyll
new_ary
end
def pop_item(array, num = nil)
return array unless array.is_a?(Array)
unless num.nil?
num = Liquid::Utils.to_integer(num)
array.pop(num)
else
array.pop
end
end
def push(array, input)
return array unless array.is_a?(Array)

View File

@@ -1256,6 +1256,26 @@ class TestFilters < JekyllUnitTest
end
end
context "pop_item filter" do
should "return the last item in the array by default" do
assert_equal "greeting", @filter.pop_item(%w(just a friendly greeting))
end
should "have the input array retain updates" do
greeting = %w(just a friendly greeting)
@filter.pop_item(greeting)
assert_equal %w(just a friendly), greeting
end
should "return multiple items popped" do
assert_equal %w(friendly greeting), @filter.pop_item(%w(just a friendly greeting), 2)
end
should "return an array when a number is specified" do
assert_equal %w(greeting), @filter.pop_item(%w(just a friendly greeting), 1)
end
should "cast string inputs for numbers into actual numbers" do
assert_equal %w(friendly greeting), @filter.pop_item(%w(just a friendly greeting), "2")
end
end
context "sample filter" do
should "return a random item from the array" do
input = %w(hey there bernie)