require 'test/spec'
require 'pyrosoma/template'
context "Pyrosoma::Template" do
def should_expand_to(template, output, &block)
Pyrosoma::Template.new(template).expand(self, &block).should.equal output
end
def foo; 42; end
def bar; "quux"; end
def xml; ""; end
specify "should work with plain text" do
should_expand_to <<'TEMPLATE', <<'OUTPUT'
hello!
TEMPLATE
hello!
OUTPUT
should_expand_to <<'TEMPLATE', <<'OUTPUT'
TEMPLATE
OUTPUT
end
specify "should ignore comments" do
should_expand_to <<'TEMPLATE', <<'OUTPUT'
$# comment
TEMPLATE
OUTPUT
should_expand_to <<'TEMPLATE', <<'OUTPUT'
1
$#two#$2$#yada#$3
4
TEMPLATE
1
23
4
OUTPUT
end
specify "should join lines ending with \\" do
should_expand_to <<'TEMPLATE', <<'OUTPUT'
line 1 \
line 2
TEMPLATE
line 1 line 2
OUTPUT
# trailing space!
should_expand_to <<'TEMPLATE', <<'OUTPUT'
line 1 \
line 2
TEMPLATE
line 1 \
line 2
OUTPUT
end
specify "should execute lines starting with $" do
should_expand_to <<'TEMPLATE', <<'OUTPUT'
1
$ 2.upto(4) { |i|
$i
$ }
5
TEMPLATE
1
2
3
4
5
OUTPUT
should_expand_to <<'TEMPLATE', <<'OUTPUT'
$ if true
YES
$ else
NO
$ end
$ if false
NO
$ else
YES
$ end
TEMPLATE
YES
YES
OUTPUT
should_expand_to <<'TEMPLATE', <<'OUTPUT'
$ a = [1,2,3]
${a[2]}
${a[4]}
${a[4]}$#
TEMPLATE
3
OUTPUT
end
specify "should support nesting" do
should_expand_to <<'TEMPLATE', <<'OUTPUT'
$ 3.times { |i|
$ 3.times { |j|
${i*j}
$ }
$ }
TEMPLATE
0
0
0
0
1
2
0
2
4
OUTPUT
end
specify "should expand terms in various ways" do
should_expand_to <<'TEMPLATE', <<'OUTPUT'
$foo
$bar
$foo\
$bar
$foo$bar
$bar.reverse
$bar.upcase.reverse
TEMPLATE
42
quux
42quux
42quux
xuuq
XUUQ
OUTPUT
@foo = 69
should_expand_to <<'TEMPLATE', <<'OUTPUT'
${foo}
${bar}
${foo}\
${bar}
${foo}${bar}
${bar.reverse}
${bar.upcase.reverse}
$bar.upcase.reverse
${2+2}
${@foo}
$@foo
$bar.reverse!
$bar.upcase!
$bar.upcase!.reverse!
TEMPLATE
42
quux
42quux
42quux
xuuq
XUUQ
XUUQ
4
69
69
xuuq
QUUX
XUUQ
OUTPUT
end
specify "should escape $$" do
should_expand_to <<'TEMPLATE', <<'OUTPUT'
$bar$$bar$$$bar$$$$bar
$$$$$$
$$$$$#foo#$$$
TEMPLATE
quux$bar$quux$$bar
$$$
$$$
OUTPUT
end
specify "should HTML escape by default" do
should_expand_to <<'TEMPLATE', <<'OUTPUT'
$xml
$:xml
TEMPLATE
<tag />
OUTPUT
end
specify "should detect parse errors" do
lambda {
Pyrosoma::Template.new("bla$(foo)quux")
}.should.raise(RuntimeError)
end
specify "should support yield" do
should_expand_to <<'TEMPLATE', <<'OUTPUT' do
${block.call}
${block.call}
TEMPLATE
foo
foo
OUTPUT
"foo"
end
end
end