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

Allow to use a custom function to compile the escape pattern (<%- %>) #12

Open
wants to merge 2 commits 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
19 changes: 11 additions & 8 deletions lib/ejs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class << self
attr_accessor :evaluation_pattern
attr_accessor :interpolation_pattern
attr_accessor :escape_pattern
attr_accessor :escape_function

# Compiles an EJS template to a JavaScript function. The compiled
# function takes an optional argument, an object specifying local
Expand Down Expand Up @@ -69,7 +70,7 @@ def js_unescape!(source)

def replace_escape_tags!(source, options)
source.gsub!(options[:escape_pattern] || escape_pattern) do
"',(''+#{js_unescape!($1)})#{escape_function},'"
"',#{runtime_escape!(js_unescape!($1))},'"
end
end

Expand All @@ -85,17 +86,19 @@ def replace_interpolation_tags!(source, options)
end
end

def escape_function
".replace(/&/g, '&amp;')" +
".replace(/</g, '&lt;')" +
".replace(/>/g, '&gt;')" +
".replace(/\"/g, '&quot;')" +
".replace(/'/g, '&#x27;')" +
".replace(/\\//g,'&#x2F;')"
def runtime_escape!(expression)
escape_function % expression
end
end

self.evaluation_pattern = /<%([\s\S]+?)%>/
self.interpolation_pattern = /<%=([\s\S]+?)%>/
self.escape_pattern = /<%-([\s\S]+?)%>/
self.escape_function =
"('' + %s).replace(/&/g, '&amp;')" +
".replace(/</g, '&lt;')" +
".replace(/>/g, '&gt;')" +
".replace(/\"/g, '&quot;')" +
".replace(/'/g, '&#x27;')" +
".replace(/\\//g,'&#x2F;')"
end
19 changes: 19 additions & 0 deletions test/test_ejs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,25 @@ class EJSCompilationTest < Test::Unit::TestCase
end
end

class EJSCustomEscapeFunctionTest < Test::Unit::TestCase
extend TestHelper

def setup
@original_escape_function = EJS.escape_function
EJS.escape_function = '_.escape(%s)'
end

def teardown
EJS.escape_function = @original_escape_function
end

test 'compile' do
result = EJS.compile('<%- name %>')
assert_match /_\.escape\(\s*name\s*\)/, result
end

end

class EJSCustomPatternTest < Test::Unit::TestCase
extend TestHelper

Expand Down