Skip to content

Commit

Permalink
Merge pull request #1875 from jekyll/benbalter-where-filter
Browse files Browse the repository at this point in the history
  • Loading branch information
mattr- committed Jan 4, 2014
2 parents 60a231f + a5f1bc0 commit 7d8c01d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
13 changes: 12 additions & 1 deletion lib/jekyll/filters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,6 @@ def jsonify(input)
input.to_json
end


# Group an array of items by a property
#
# input - the inputted Enumerable
Expand All @@ -179,6 +178,18 @@ def group_by(input, property)
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
def time(input)
case input
Expand Down
17 changes: 17 additions & 0 deletions test/test_filters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ def initialize(opts = {})
@filter = JekyllFilter.new({"source" => source_dir, "destination" => dest_dir})
@sample_time = Time.utc(2013, 03, 27, 11, 22, 33)
@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

should "textilize with simple string" do
Expand Down Expand Up @@ -131,5 +136,17 @@ def initialize(opts = {})
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

0 comments on commit 7d8c01d

Please sign in to comment.