From 18e8ce1eb05af73daa7b8cc3258d8e67ec388f5d Mon Sep 17 00:00:00 2001 From: Arthur Neves Date: Thu, 15 Aug 2013 16:06:56 -0400 Subject: [PATCH] add flatten filter --- lib/liquid/standardfilters.rb | 7 ++++++- test/integration/standard_filter_test.rb | 10 ++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/liquid/standardfilters.rb b/lib/liquid/standardfilters.rb index 849fe22..7bd9cd8 100644 --- a/lib/liquid/standardfilters.rb +++ b/lib/liquid/standardfilters.rb @@ -101,7 +101,7 @@ module Liquid ary = InputIterator.new(input) if property.nil? ary.sort - elsif ary.first.respond_to?('[]'.freeze) and !ary.first[property].nil? + elsif ary.first.respond_to?('[]'.freeze) && !ary.first[property].nil? ary.sort {|a,b| a[property] <=> b[property] } elsif ary.first.respond_to?(property) ary.sort {|a,b| a.send(property) <=> b.send(property) } @@ -127,6 +127,11 @@ module Liquid end end + # flatten the given input + def flatten(input) + Array(input).flatten + end + # Replace occurrences of a string with another def replace(input, string, replacement = ''.freeze) input.to_s.gsub(string, replacement.to_s) diff --git a/test/integration/standard_filter_test.rb b/test/integration/standard_filter_test.rb index 7b417ae..50f93c6 100644 --- a/test/integration/standard_filter_test.rb +++ b/test/integration/standard_filter_test.rb @@ -149,6 +149,16 @@ class StandardFiltersTest < Test::Unit::TestCase "thing" => { "foo" => [ { "bar" => 42 }, { "bar" => 17 } ] } end + def test_flatten + assert_equal [1,2,3,4], @filters.flatten([1,2,3,4]) + assert_equal [1,2,3,4], @filters.flatten([[1,2,3,4]]) + assert_equal [1,2,3,4], @filters.flatten([[1],[2],[3],[4]]) + assert_equal [1], @filters.flatten(1) + + assert_template_result '1234', "{{ ary | flatten | flatten }}", + 'ary' => [[1],2,[3],4] + end + def test_sort_calls_to_liquid t = TestThing.new Liquid::Template.parse('{{ foo | sort: "whatever" }}').render("foo" => [t])