Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Extract json string escaping

  • Loading branch information...
commit 4a8d2ef0a552e04d6cb35b91e23dd3979783b586 1 parent 5577d56
@jeremy jeremy authored
View
38 activesupport/lib/active_support/json.rb
@@ -11,6 +11,33 @@ module JSON
# matches YAML-formatted dates
DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[ \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
+ module Encoding #:nodoc:
+ mattr_accessor :escape_regex
+
+ ESCAPED_CHARS = {
+ "\010" => '\b',
+ "\f" => '\f',
+ "\n" => '\n',
+ "\r" => '\r',
+ "\t" => '\t',
+ '"' => '\"',
+ '\\' => '\\\\',
+ '>' => '\u003E',
+ '<' => '\u003C',
+ '&' => '\u0026'
+ }
+
+ def self.escape(string)
+ json = '"' + string.gsub(escape_regex) { |s| ESCAPED_CHARS[s] }
+ json.force_encoding('ascii-8bit') if respond_to?(:force_encoding)
+ json.gsub(/([\xC0-\xDF][\x80-\xBF]|
+ [\xE0-\xEF][\x80-\xBF]{2}|
+ [\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s|
+ s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&')
+ } + '"'
+ end
+ end
+
class << self
attr_reader :backend
delegate :decode, :to => :backend
@@ -34,9 +61,7 @@ def with_backend(name)
end
class << self
- def escape_html_entities_in_json
- @escape_html_entities_in_json
- end
+ attr_reader :escape_html_entities_in_json
def escape_html_entities_in_json=(value)
ActiveSupport::JSON::Encoding.escape_regex = \
@@ -48,8 +73,9 @@ def escape_html_entities_in_json=(value)
@escape_html_entities_in_json = value
end
end
-
- JSON.backend = 'Yaml'
end
-require 'active_support/json/encoding'
+ActiveSupport.escape_html_entities_in_json = true
+ActiveSupport::JSON.backend = 'Yaml'
+
+require 'active_support/json/encoding'
View
33 activesupport/lib/active_support/json/encoders/string.rb
@@ -1,36 +1,5 @@
-module ActiveSupport
- module JSON
- module Encoding
- mattr_accessor :escape_regex
-
- ESCAPED_CHARS = {
- "\010" => '\b',
- "\f" => '\f',
- "\n" => '\n',
- "\r" => '\r',
- "\t" => '\t',
- '"' => '\"',
- '\\' => '\\\\',
- '>' => '\u003E',
- '<' => '\u003C',
- '&' => '\u0026'
- }
- end
- end
-end
-
-ActiveSupport.escape_html_entities_in_json = true
-
class String
def rails_to_json(options = nil) #:nodoc:
- json = '"' + gsub(ActiveSupport::JSON::Encoding.escape_regex) { |s|
- ActiveSupport::JSON::Encoding::ESCAPED_CHARS[s]
- }
- json.force_encoding('ascii-8bit') if respond_to?(:force_encoding)
- json.gsub(/([\xC0-\xDF][\x80-\xBF]|
- [\xE0-\xEF][\x80-\xBF]{2}|
- [\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s|
- s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&')
- } + '"'
+ ActiveSupport::JSON::Encoding.escape(self)
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.