lib/json/pure/generator.rb in json_pure-1.1.9 vs lib/json/pure/generator.rb in json_pure-1.2.0
- old
+ new
@@ -36,15 +36,15 @@
'\\' => '\\\\',
} # :nodoc:
# Convert a UTF8 encoded Ruby string _string_ to a JSON string, encoded with
# UTF16 big endian characters as \u????, and return it.
- if String.method_defined?(:force_encoding)
+ if defined?(::Encoding)
def utf8_to_json(string) # :nodoc:
string = string.dup
string << '' # XXX workaround: avoid buffer sharing
- string.force_encoding(Encoding::ASCII_8BIT)
+ string.force_encoding(::Encoding::ASCII_8BIT)
string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] }
string.gsub!(/(
(?:
[\xc2-\xdf][\x80-\xbf] |
[\xe0-\xef][\x80-\xbf]{2} |
@@ -54,11 +54,11 @@
)/nx) { |c|
c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'"
s = JSON::UTF8toUTF16.iconv(c).unpack('H*')[0]
s.gsub!(/.{4}/n, '\\\\u\&')
}
- string.force_encoding(Encoding::UTF_8)
+ string.force_encoding(::Encoding::UTF_8)
string
rescue Iconv::Failure => e
raise GeneratorError, "Caught #{e.class}: #{e}"
end
else
@@ -349,17 +349,17 @@
module Float
# Returns a JSON string representation for this Float number.
def to_json(state = nil, *)
case
when infinite?
- if !state || state.allow_nan?
+ if state && state.allow_nan?
to_s
else
raise GeneratorError, "#{self} not allowed in JSON"
end
when nan?
- if !state || state.allow_nan?
+ if state && state.allow_nan?
to_s
else
raise GeneratorError, "#{self} not allowed in JSON"
end
else
@@ -367,14 +367,28 @@
end
end
end
module String
- # This string should be encoded with UTF-8 A call to this method
- # returns a JSON string encoded with UTF16 big endian characters as
- # \u????.
- def to_json(*)
- '"' << JSON.utf8_to_json(self) << '"'
+ if defined?(::Encoding)
+ # This string should be encoded with UTF-8 A call to this method
+ # returns a JSON string encoded with UTF16 big endian characters as
+ # \u????.
+ def to_json(*)
+ if encoding == ::Encoding::UTF_8
+ '"' << JSON.utf8_to_json(self) << '"'
+ else
+ string = encode(::Encoding::UTF_8)
+ '"' << JSON.utf8_to_json(string) << '"'
+ end
+ end
+ else
+ # This string should be encoded with UTF-8 A call to this method
+ # returns a JSON string encoded with UTF16 big endian characters as
+ # \u????.
+ def to_json(*)
+ '"' << JSON.utf8_to_json(self) << '"'
+ end
end
# Module that holds the extinding methods if, the String module is
# included.
module Extend