From 31620d0c0aea9a10219b912e76817e5303e3b8bb Mon Sep 17 00:00:00 2001 From: Holger Just Date: Tue, 17 Jan 2012 13:47:13 +0100 Subject: [PATCH] Override first and last filters to allow simple array slicing --- lib/chili_project/liquid/filters.rb | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/lib/chili_project/liquid/filters.rb b/lib/chili_project/liquid/filters.rb index c598a890..4e4a8d07 100644 --- a/lib/chili_project/liquid/filters.rb +++ b/lib/chili_project/liquid/filters.rb @@ -44,6 +44,26 @@ module ChiliProject def replace_first(input, string, replacement = '') input.to_s.sub(string){replacement} end + + # Get the first element(s) of the passed in array + # Example: + # {{ product.images | first | to_img }} + def first(array, count=nil) + return array.first if count.nil? && array.respond_to?(:first) + if array.respond_to?(:[]) + count.to_i > 0 ? array[0..count.to_i-1] : [] + end + end + + # Get the last element(s) of the passed in array + # Example: + # {{ product.images | last | to_img }} + def last(array, count=nil) + array.last if count=nil? && array.respond_to?(:last) + if array.respond_to?(:[]) + count.to_i > 0 ? array[(count.to_i * -1)..-1] : [] + end + end end module Filters