diff --git a/lib/ejs.rb b/lib/ejs.rb index 686649a..413d986 100644 --- a/lib/ejs.rb +++ b/lib/ejs.rb @@ -69,7 +69,7 @@ def js_unescape!(source) def replace_escape_tags!(source, options) source.gsub!(options[:escape_pattern] || escape_pattern) do - "',(''+#{js_unescape!($1)})#{escape_function},'" + "',#{coerce_to_string_function}(#{js_unescape!($1)})#{escape_function},'" end end @@ -85,6 +85,12 @@ def replace_interpolation_tags!(source, options) end end + def coerce_to_string_function + "function(s) {" + + "return (s === null || typeof(s) === 'undefined') ? '' : ('' + s);" + + "}" + end + def escape_function ".replace(/&/g, '&')" + ".replace(/ "'Foo Bar'" }) + + template = "<%- null %>" + assert_equal "", EJS.evaluate(template, {}) + + template = "<%- undefined %>" + assert_equal "", EJS.evaluate(template, {}) end test "braced escaping" do @@ -182,6 +188,12 @@ class EJSEvaluationTest < Test::Unit::TestCase template = "{{- foobar }}" assert_equal "'Foo Bar'", EJS.evaluate(template, { :foobar => "'Foo Bar'" }, BRACE_SYNTAX) + + template = "{{- null }}" + assert_equal "", EJS.evaluate(template, {}, BRACE_SYNTAX) + + template = "{{- undefined }}" + assert_equal "", EJS.evaluate(template, {}, BRACE_SYNTAX) end test "question-mark escaping" do @@ -196,5 +208,11 @@ class EJSEvaluationTest < Test::Unit::TestCase template = "" assert_equal "'Foo Bar'", EJS.evaluate(template, { :foobar => "'Foo Bar'" }, QUESTION_MARK_SYNTAX) + + template = "" + assert_equal "", EJS.evaluate(template, {}, QUESTION_MARK_SYNTAX) + + template = "" + assert_equal "", EJS.evaluate(template, {}, QUESTION_MARK_SYNTAX) end end