Skip to content

Commit

Permalink
add a more robust json_escape method
Browse files Browse the repository at this point in the history
  • Loading branch information
dewski committed May 24, 2012
1 parent 8170b95 commit ea09699
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
17 changes: 13 additions & 4 deletions lib/json_builder/extensions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,26 @@ def to_builder
end

class String
JS_ESCAPE_MAP = {
'\\' => '\\\\',
'</' => '<\/',
"\r\n" => '\n',
"\n" => '\n',
"\r" => '\n',
'"' => '\\"',
"'" => "\\'"
}

def to_builder
%("#{json_escape}")
end

private

def json_escape
self.gsub(/\n/, '\\n').
gsub(/\r/, '\\r').
gsub(/\t/, '\\t').
gsub(/\f/, '\\f')
gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) { |match|
JS_ESCAPE_MAP[match]
}
end
end

Expand Down
4 changes: 4 additions & 0 deletions test/member_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ def test_custom_class
assert_equal '"hello": "olleh"', member('hello', Dozer.new('hello')).to_s
end

def test_double_quoted_value
assert_equal '"hello": "\"Hello\" he said"', member('hello', '"Hello" he said').to_s
end

def test_without_key
assert_raises(JSONBuilder::MissingKeyError) { member(nil, true).to_s }
end
Expand Down
4 changes: 4 additions & 0 deletions test/value_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,8 @@ def test_hash_value
def test_custom_class
assert_equal '"olleh"', value(Dozer.new('hello'))
end

def test_double_quoted_value
assert_equal '"\"hello\""', value('"hello"')
end
end

0 comments on commit ea09699

Please sign in to comment.