Merge pull request #1875 from jekyll/benbalter-where-filter

This commit is contained in:
Matt Rogers 2014-01-04 08:01:53 -08:00
commit 7d8c01dbf4
2 changed files with 29 additions and 1 deletions

View File

@ -158,7 +158,6 @@ module Jekyll
input.to_json input.to_json
end end
# Group an array of items by a property # Group an array of items by a property
# #
# input - the inputted Enumerable # input - the inputted Enumerable
@ -179,6 +178,18 @@ module Jekyll
end end
end end
# Filter an array of objects
#
# input - the object array
# key - key within each object to filter by
# value - desired value
#
# Returns the filtered array of objects
def where(input, key, value)
return input unless input.is_a?(Array)
input.select { |object| object[key] == value }
end
private private
def time(input) def time(input)
case input case input

View File

@ -16,6 +16,11 @@ class TestFilters < Test::Unit::TestCase
@filter = JekyllFilter.new({"source" => source_dir, "destination" => dest_dir}) @filter = JekyllFilter.new({"source" => source_dir, "destination" => dest_dir})
@sample_time = Time.utc(2013, 03, 27, 11, 22, 33) @sample_time = Time.utc(2013, 03, 27, 11, 22, 33)
@time_as_string = "September 11, 2001 12:46:30 -0000" @time_as_string = "September 11, 2001 12:46:30 -0000"
@array_of_objects = [
{ "color" => "red", "size" => "large" },
{ "color" => "red", "size" => "medium" },
{ "color" => "blue", "size" => "medium" }
]
end end
should "textilize with simple string" do should "textilize with simple string" do
@ -131,5 +136,17 @@ class TestFilters < Test::Unit::TestCase
end end
end end
end end
context "where filter" do
should "return any input that is not an array" do
assert_equal Hash.new, @filter.where(Hash.new, nil, nil)
assert_equal "some string", @filter.where("some string", "la", "le")
end
should "filter objects appropriately" do
assert_equal 2, @filter.where(@array_of_objects, "color", "red").length
end
end
end end
end end