From ca2fa587cf224e59f46bbeda0de538fba1cf6217 Mon Sep 17 00:00:00 2001 From: Michael Richardson Date: Tue, 31 Aug 2010 16:17:12 -0400 Subject: [PATCH] added tag to increment a variable each time it is referenced --- lib/liquid/tags/inc.rb | 37 +++++++++++++++++++++++++++++++++++++ test/inc_tag_test.rb | 16 ++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 lib/liquid/tags/inc.rb create mode 100644 test/inc_tag_test.rb diff --git a/lib/liquid/tags/inc.rb b/lib/liquid/tags/inc.rb new file mode 100644 index 0000000..be140c0 --- /dev/null +++ b/lib/liquid/tags/inc.rb @@ -0,0 +1,37 @@ +#require 'rubygems' +#require 'ruby-debug' + +module Liquid + + # inc is used in a place where one needs to insert a counter + # into a template, and needs the counter to survive across + # multiple instantiations of the template. + # + # if the variable does not exist, it is created with value 0. + + # Hello: {% inc variable %} + # + # gives you: + # + # Hello: 0 + # Hello: 1 + # Hello: 2 + # + class Inc < Tag + def initialize(tag_name, markup, tokens) + @variable = markup.strip + + super + end + + def render(context) + value = context.registers[@variable] ||= 0 + context.registers[@variable] = value + 1 + value.to_s + end + + private + end + + Template.register_tag('inc', Inc) +end diff --git a/test/inc_tag_test.rb b/test/inc_tag_test.rb new file mode 100644 index 0000000..cb4daa7 --- /dev/null +++ b/test/inc_tag_test.rb @@ -0,0 +1,16 @@ +require File.dirname(__FILE__) + '/helper' + + +class IncTagTest < Test::Unit::TestCase + include Liquid + + def test_inc + assert_template_result('0','{%inc port %}') + assert_template_result('0 1','{%inc port %} {%inc port%}') + assert_template_result('0 0 1 2 1', + '{%inc port %} {%inc starboard%} ' + + '{%inc port %} {%inc port%} ' + + '{%inc starboard %}') + end + +end