Permalink
Browse files

fix text processing, execute helper code blocks

  • Loading branch information...
1 parent 146da88 commit 6320ea9a397404eb56b6634fd1940bd2a3988c06 @igrigorik committed Oct 27, 2011
@@ -26,7 +26,9 @@ def add_expr(src, code, indicator)
end
def add_text(src, text)
- src << " #{@bufvar}.writeSafe '" << text << "';" unless text.empty?
+ if !text.empty?
+ src << " #{@bufvar}.writeSafe '" << text.to_s.gsub("'", "\\\\'") << "';"
+ end
end
def add_stmt(src, code)
@@ -39,7 +41,7 @@ def add_expr_literal(src, code)
end
def add_expr_escaped(src, code)
- src << " #{@bufvar}.write((" << code << ').to_s);'
+ src << " #{@bufvar}.write(" << code << ').to_s;'
end
end
File renamed without changes.
File renamed without changes.
View
@@ -1,5 +1,28 @@
require "contextual"
+TEMPLATE = <<-eos
+<% def helper(obj); "Hello, \#{obj['world']}"; end %>
+
+<div style="color: <%= object['color'] %>">
+<a href="/<%= object['color'] %>?q=<%= object['world'] %>" onclick="alert('<%= helper(object) %>');return false"><%= helper(object) %></a>
+<script>(function () { // Sleepy developers put sensitive info in comments.
+ var o = <%= object %>,
+ w = "<%= object['world'] %>";
+})();</script>
+</div>
+eos
+
+EXPECTED = <<-eos
+
+<div style="color: blue">
+<a href="/blue?q=%3cCincinnati%3e" onclick="alert('Hello, \\x3cCincinnati\\x3e');return false">Hello, &lt;Cincinnati&gt;</a>
+<script>(function () {
+ var o = {'world':'\\x3cCincinnati\\x3e','color':'blue'},
+ w = "\\x3cCincinnati\\x3e";
+})();</script>
+</div>
+eos
+
describe Contextual do
it "should escape unsafe content" do
@@ -32,4 +55,17 @@
t.result.should be_empty
end
+ it "should render contextual template" do
+
+ object = {"world" => "<Cincinnati>", "color" => "blue"}
+ template = Erubis::ContextualEruby.new(TEMPLATE)
+ res = template.result(binding())
+
+ # don't worry about trailing whitespace
+ res = res.split("\n").map {|r| r.strip}
+ exp = EXPECTED.split("\n").map {|r| r.strip}
+
+ res.should == exp
+ end
+
end

0 comments on commit 6320ea9

Please sign in to comment.