add where filter to filter arrays of objects
This commit is contained in:
parent
60a231f16d
commit
39e4d6b3ba
|
@ -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.class == Array
|
||||||
|
input.select { |object| object[key] == value }
|
||||||
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
def time(input)
|
def time(input)
|
||||||
case input
|
case input
|
||||||
|
|
|
@ -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
|
||||||
|
@ -109,6 +114,11 @@ class TestFilters < Test::Unit::TestCase
|
||||||
assert_equal "[1,2]", @filter.jsonify([1, 2])
|
assert_equal "[1,2]", @filter.jsonify([1, 2])
|
||||||
assert_equal "[{\"name\":\"Jack\"},{\"name\":\"Smith\"}]", @filter.jsonify([{:name => 'Jack'}, {:name => 'Smith'}])
|
assert_equal "[{\"name\":\"Jack\"},{\"name\":\"Smith\"}]", @filter.jsonify([{:name => 'Jack'}, {:name => 'Smith'}])
|
||||||
end
|
end
|
||||||
|
|
||||||
|
should "proper filter objects using where" do
|
||||||
|
assert_equal "some string", @filter.where("some string", nil, nil)
|
||||||
|
assert_equal 2, @filter.where(@array_of_objects, "color", "red").length
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
context "group_by filter" do
|
context "group_by filter" do
|
||||||
|
|
Loading…
Reference in New Issue