Skip to content
This repository has been archived by the owner on Jun 10, 2018. It is now read-only.

Coerce null/undefined to empty string when escaping #16

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/ejs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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(/</g, '&lt;')" +
Expand Down
18 changes: 18 additions & 0 deletions test/test_ejs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,12 @@ class EJSEvaluationTest < Test::Unit::TestCase

template = "<%- foobar %>"
assert_equal "&#x27;Foo Bar&#x27;", EJS.evaluate(template, { :foobar => "'Foo Bar'" })

template = "<%- null %>"
assert_equal "", EJS.evaluate(template, {})

template = "<%- undefined %>"
assert_equal "", EJS.evaluate(template, {})
end

test "braced escaping" do
Expand All @@ -182,6 +188,12 @@ class EJSEvaluationTest < Test::Unit::TestCase

template = "{{- foobar }}"
assert_equal "&#x27;Foo Bar&#x27;", 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
Expand All @@ -196,5 +208,11 @@ class EJSEvaluationTest < Test::Unit::TestCase

template = "<?- foobar ?>"
assert_equal "&#x27;Foo Bar&#x27;", EJS.evaluate(template, { :foobar => "'Foo Bar'" }, QUESTION_MARK_SYNTAX)

template = "<?- null ?>"
assert_equal "", EJS.evaluate(template, {}, QUESTION_MARK_SYNTAX)

template = "<?- undefined ?>"
assert_equal "", EJS.evaluate(template, {}, QUESTION_MARK_SYNTAX)
end
end