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 where filter to filter array objects #1875

Merged
merged 4 commits into from
Jan 4, 2014
Merged
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
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