Skip to content

Commit

Permalink
Implement group_by Liquid filter & tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
parkr committed Dec 8, 2013
1 parent d2e9486 commit 381ab4e
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 5 deletions.
31 changes: 30 additions & 1 deletion lib/jekyll/filters.rb
Expand Up @@ -100,7 +100,7 @@ def xml_escape(input)
def cgi_escape(input)
CGI::escape(input)
end

# URI escape a string.
#
# input - The String to escape.
Expand Down Expand Up @@ -158,6 +158,31 @@ def jsonify(input)
input.to_json
end


# Group an array of items by a property
#
# input - the inputted Enumerable
# property - the property
#
# Returns an array of Hashes, each looking something like this:
# {"name" => "larry"
# "items" => [...] } # all the items where `property` == "larry"
def group_by(input, property)
if groupable?(input)
input.group_by do |item|
if item.respond_to?(:data)
item.data[property.to_s].to_s
else
item[property.to_s].to_s
end
end.inject([]) do |memo, i|
memo << {"name" => i.first, "items" => i.last}
end
else
input
end
end

private
def time(input)
case input
Expand All @@ -170,5 +195,9 @@ def time(input)
exit(1)
end
end

def groupable?(element)
element.respond_to?(:group_by)
end
end
end
30 changes: 26 additions & 4 deletions test/test_filters.rb
Expand Up @@ -3,16 +3,17 @@
class TestFilters < Test::Unit::TestCase
class JekyllFilter
include Jekyll::Filters
attr_accessor :site, :context

def initialize
site = Jekyll::Site.new(Jekyll.configuration({}))
@context = Liquid::Context.new({}, {}, { :site => site })
def initialize(opts = {})
@site = Jekyll::Site.new(Jekyll.configuration(opts))
@context = Liquid::Context.new({}, {}, { :site => @site })
end
end

context "filters" do
setup do
@filter = JekyllFilter.new
@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"
end
Expand Down Expand Up @@ -109,5 +110,26 @@ def initialize
assert_equal "[{\"name\":\"Jack\"},{\"name\":\"Smith\"}]", @filter.jsonify([{:name => 'Jack'}, {:name => 'Smith'}])
end
end

context "group_by filter" do
should "successfully group array of Jekyll::Page's" do
@filter.site.process
grouping = @filter.group_by(@filter.site.pages, "layout")
grouping.each do |g|
assert ["default", "nil", ""].include?(g["name"]), "#{g['name']} isn't a valid grouping."
case g["name"]
when "default"
assert g["items"].is_a?(Array), "The list of grouped items for 'default' is not an Array."
assert_equal 3, g["items"].size
when "nil"
assert g["items"].is_a?(Array), "The list of grouped items for 'nil' is not an Array."
assert_equal 2, g["items"].size
when ""
assert g["items"].is_a?(Array), "The list of grouped items for '' is not an Array."
assert_equal 5, g["items"].size
end
end
end
end
end
end

0 comments on commit 381ab4e

Please sign in to comment.