From 87a5e747fd6573dd1ebef0b48f523067d6270438 Mon Sep 17 00:00:00 2001 From: Marc Chung Date: Tue, 30 Dec 2008 11:33:22 -0700 Subject: [PATCH] Added array_to_sentence_string filter --- lib/jekyll/filters.rb | 17 ++++++++++++++++- test/test_filters.rb | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 test/test_filters.rb diff --git a/lib/jekyll/filters.rb b/lib/jekyll/filters.rb index 6051626a..6cfa6361 100644 --- a/lib/jekyll/filters.rb +++ b/lib/jekyll/filters.rb @@ -19,6 +19,21 @@ module Jekyll def number_of_words(input) input.split.length - end + end + + def array_to_sentence_string(array) + connector = "and" + case array.length + when 0 + "" + when 1 + array[0].to_s + when 2 + "#{array[0]} #{connector} #{array[1]}" + else + "#{array[0...-1].join(', ')}, #{connector} #{array[-1]}" + end + end + end end \ No newline at end of file diff --git a/test/test_filters.rb b/test/test_filters.rb new file mode 100644 index 00000000..442cbc9e --- /dev/null +++ b/test/test_filters.rb @@ -0,0 +1,32 @@ +require File.dirname(__FILE__) + '/helper' + +class TestSite < Test::Unit::TestCase + + class JekyllFilter + include Jekyll::Filters + end + + def setup + @filter = JekyllFilter.new + end + + def test_array_to_sentence_string_with_no_args + assert_equal "", @filter.array_to_sentence_string([]) + end + + def test_array_to_sentence_string_with_one_arg + assert_equal "1", @filter.array_to_sentence_string([1]) + assert_equal "chunky", @filter.array_to_sentence_string(["chunky"]) + end + + def test_array_to_sentence_string_with_two_args + assert_equal "1 and 2", @filter.array_to_sentence_string([1, 2]) + assert_equal "chunky and bacon", @filter.array_to_sentence_string(["chunky", "bacon"]) + end + + def test_array_to_sentence_string_with_multiple_args + assert_equal "1, 2, 3, and 4", @filter.array_to_sentence_string([1, 2, 3, 4]) + assert_equal "chunky, bacon, bits, and pieces", @filter.array_to_sentence_string(["chunky", "bacon", "bits", "pieces"]) + end + +end \ No newline at end of file