Merge pull request #28 from mcr/mcr_inc_tag

increment tag
This commit is contained in:
Tobias Lütke
2011-07-01 11:48:13 -07:00
4 changed files with 100 additions and 0 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
*~
*.gem
*.swp
pkg

View File

@@ -0,0 +1,39 @@
module Liquid
# decrement 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.
# NOTE: decrement is a pre-decrement, --i,
# while increment is post: i++.
#
# (To achieve the survival, the application must keep the context)
#
# if the variable does not exist, it is created with value 0.
# Hello: {% decrement variable %}
#
# gives you:
#
# Hello: -1
# Hello: -2
# Hello: -3
#
class Decrement < Tag
def initialize(tag_name, markup, tokens)
@variable = markup.strip
super
end
def render(context)
value = context.environments.first[@variable] ||= 0
value = value - 1
context.environments.first[@variable] = value
value.to_s
end
private
end
Template.register_tag('decrement', Decrement)
end

View File

@@ -0,0 +1,35 @@
module Liquid
# increment 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.
# (To achieve the survival, the application must keep the context)
#
# if the variable does not exist, it is created with value 0.
# Hello: {% increment variable %}
#
# gives you:
#
# Hello: 0
# Hello: 1
# Hello: 2
#
class Increment < Tag
def initialize(tag_name, markup, tokens)
@variable = markup.strip
super
end
def render(context)
value = context.environments.first[@variable] ||= 0
context.environments.first[@variable] = value + 1
value.to_s
end
private
end
Template.register_tag('increment', Increment)
end

View File

@@ -0,0 +1,25 @@
require 'test_helper'
class IncTagTest < Test::Unit::TestCase
include Liquid
def test_inc
assert_template_result('0','{%increment port %}', {})
assert_template_result('0 1','{%increment port %} {%increment port%}', {})
assert_template_result('0 0 1 2 1',
'{%increment port %} {%increment starboard%} ' +
'{%increment port %} {%increment port%} ' +
'{%increment starboard %}', {})
end
def test_dec
assert_template_result('9','{%decrement port %}', { 'port' => 10})
assert_template_result('-1 -2','{%decrement port %} {%decrement port%}', {})
assert_template_result('1 5 2 2 5',
'{%increment port %} {%increment starboard%} ' +
'{%increment port %} {%decrement port%} ' +
'{%decrement starboard %}', { 'port' => 1, 'starboard' => 5 })
end
end