Permalink
Browse files

Escape newline/return/tab characters

Fixes #23
  • Loading branch information...
1 parent 0f6fbad commit e5c3cf25a0eeb2726e8705053ff8037fbd7eb4da @dewski dewski committed Apr 4, 2012
Showing with 21 additions and 6 deletions.
  1. +15 −6 lib/json_builder/extensions.rb
  2. +6 −0 test/compiler_test.rb
@@ -14,7 +14,16 @@ def to_builder
class String
def to_builder
- "\"#{self}\""
+ %("#{json_escape}")
+ end
+
+ private
+
+ def json_escape
+ self.gsub(/\n/, '\\n')
+ .gsub(/\r/, '\\r')
+ .gsub(/\t/, '\\t')
+ .gsub(/\f/, '\\f')
end
end
@@ -33,33 +42,33 @@ def to_builder
module ActiveSupport
class TimeWithZone
def to_builder
- "\"#{iso8601}\""
+ %("#{iso8601}")
end
end
end
class Time
def to_builder
- "\"#{iso8601}\""
+ %("#{iso8601}")
end
end
class Date
def to_builder
- "\"#{to_time.iso8601}\""
+ %("#{to_time.iso8601}")
end
end
class DateTime
def to_builder
- "\"#{to_time.iso8601}\""
+ %("#{to_time.iso8601}")
end
end
module BSON
class ObjectId
def to_builder
- "\"#{self}\""
+ %("#{self}")
end
end
end
View
@@ -94,4 +94,10 @@ def test_adding_unicoded_key
key 'é', 'json'
end
end
+
+ def test_newline_characters
+ assert_builder_json('{"newline": "hello\nworld"}') do
+ newline "hello\nworld"
+ end
+ end
end

0 comments on commit e5c3cf2

Please sign in to comment.