Skip to content

Commit

Permalink
Improve escapes with a bs.js library
Browse files Browse the repository at this point in the history
I resisted this, but it makes BS more useful, so what can you do?
  • Loading branch information
mxcl committed Mar 16, 2013
1 parent c3871fe commit 2770f73
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 21 deletions.
4 changes: 2 additions & 2 deletions BullScript.JSON-tmLanguage
Expand Up @@ -8,7 +8,7 @@
"0": { "name": "string.quoted.double.js" }
},
"patterns": [
{ "begin": "#[nxX]?{",
{ "begin": "#[nNxX]?{",
"end": "}",
"patterns": [
{ "include": "$self" }
Expand All @@ -28,7 +28,7 @@
"1": { "name": "entity.name.tag.html" }
},
"patterns": [
{ "begin": "#[nxX]?{",
{ "begin": "#[nNxX]?{",
"end": "}",
"patterns": [
{ "include": "$self" }
Expand Down
26 changes: 26 additions & 0 deletions bs.js
@@ -0,0 +1,26 @@
(function() {
bs = {
x: function(y) {
if (y === null || y === undefined)
return '';
return encodeURIComponent(y).replace('%20', '+');
},
X: function(y) {
if (y === null || y === undefined)
return '';
return encodeURIComponent(y).replace(/[!'()]/g, escape).replace(/\*/g, '%2A');
},
n: function(y) {
if (y === null || y === undefined)
return '';
return y;
},
N: function(y) {
if (y instanceof Array && y.length <= 0)
return '';
if (y instanceof Object && Object.keys(y).length <= 0)
return '';
return y || '';
}
};
})();
13 changes: 4 additions & 9 deletions bsc
Expand Up @@ -141,16 +141,11 @@ end

class String
def bsubst sep = '"'
self.gsub(/#([nxX]?)\{(.*?)\}/) do
inner = case $1
when 'n'
"((#{$2}) || '')"
when 'X'
"encodeURIComponent(#{$2}).replace(/[!'()]/g, escape).replace(/\\*/g, '%2A')"
when 'x'
"encodeURIComponent(#{$2}).replace('%20', '+')"
self.gsub(/#([nNxX]?)\{(.*?)\}/) do
inner = if $1 and $1.length > 0
"bs.#$1(#$2)"
else
"(#{$2})"
"(#$2)"
end
%Q{#{sep} + #{inner} + #{sep}}
end
Expand Down
21 changes: 11 additions & 10 deletions tests
Expand Up @@ -62,11 +62,11 @@ class BullTests < Test::Unit::TestCase
end

def test_falsy_subst
assert_equal %q{"foo #n{bar} foo"}.to_js, %q{"foo " + ((bar) || '') + " foo"}
assert_equal %q{"foo #n{bar} foo"}.to_js, %q{"foo " + bs.n(bar) + " foo"}
end

def test_URI_encoded_subst
assert_equal %q{"foo #x{bar} foo"}.to_js, %q{"foo " + encodeURIComponent(bar).replace('%20', '+') + " foo"}
assert_equal %q{"foo #x{bar} foo"}.to_js, %q{"foo " + bs.x(bar) + " foo"}
end

def test_html1
Expand Down Expand Up @@ -197,15 +197,16 @@ class BullTests < Test::Unit::TestCase

def test_multiline_with_internal_quotes
input = <<-end.to_js
"""foo
bar \#{jee || ''} haha
mooface
"""
"""foo
bar \#{jee || ''} haha
mooface
"""
end
output = <<-end.to_js
'foo\n'+
'bar ' + (jee || '') + ' haha\n'+
'mooface\n'+
''
'foo\\n'+
'bar ' + (jee || '') + ' haha\\n'+
'mooface\\n'+
''
end
assert_equal output, input
end
Expand Down

0 comments on commit 2770f73

Please sign in to comment.