Permalink
Browse files

Improve escapes with a `bs.js` library

I resisted this, but it makes BS more useful, so what can you do?
  • Loading branch information...
1 parent c3871fe commit 2770f736e3dc25cde8c80c9a7b5806e65dc19674 @mxcl committed Mar 16, 2013
Showing with 43 additions and 21 deletions.
  1. +2 −2 BullScript.JSON-tmLanguage
  2. +26 −0 bs.js
  3. +4 −9 bsc
  4. +11 −10 tests
@@ -8,7 +8,7 @@
"0": { "name": "string.quoted.double.js" }
},
"patterns": [
- { "begin": "#[nxX]?{",
+ { "begin": "#[nNxX]?{",
"end": "}",
"patterns": [
{ "include": "$self" }
@@ -28,7 +28,7 @@
"1": { "name": "entity.name.tag.html" }
},
"patterns": [
- { "begin": "#[nxX]?{",
+ { "begin": "#[nNxX]?{",
"end": "}",
"patterns": [
{ "include": "$self" }
View
26 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 || '';
+ }
+ };
+})();
View
13 bsc
@@ -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
View
21 tests
@@ -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
@@ -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

0 comments on commit 2770f73

Please sign in to comment.