Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 33 additions & 13 deletions lib/json/add/string.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,52 @@
require 'json'
end

# == Binary \String As \JSON
#
# Here is a strategy for converting a binary string to \JSON,
# and converting the \JSON back to a string.
#
# Construct a binary string with ASCII-8BIT encoding.
#
# binary_s = ''.b # Empty binary string.
# (0..3).each {|i| binary_s << i } # Populate the string.
# binary_s # => "\x00\x01\x02\x03"
# binary_s.encoding # => #<Encoding:BINARY (ASCII-8BIT)>
#
# Convert the binary string to a specially-formatted \JSON string with UTF-8 encoding:
#
# json_s = binary_s.to_json_raw # => "{\"json_class\":\"String\",\"raw\":[0,1,2,3]}"
# json_s.encoding # => #<Encoding:UTF-8>
#
# Convert the specially-formatted \JSON string to a hash,
# then to a binary string with ASCII-8BIT encoding:
#
# hash = JSON.parse(json_s) # => {"json_class" => "String", "raw" => [0, 1, 2, 3]}
# binary_s = String.json_create(hash) # => "\x00\x01\x02\x03"
# binary_s.encoding # => #<Encoding:BINARY (ASCII-8BIT)>
#
class String
# call-seq: json_create(o)
# call-seq:
# self.json_create(hash) -> new_string
#
# Raw Strings are JSON Objects (the raw bytes are stored in an array for the
# key "raw"). The Ruby String can be created by this class method.
# Returns a binary string with ASCII-8BIT encoding, converted from a specially formatted hash;
# see {Binary String As JSON}[rdoc-ref:String@Binary+String+As+JSON].
def self.json_create(object)
object["raw"].pack("C*")
end

# call-seq: to_json_raw_object()
#
# This method creates a raw object hash, that can be nested into
# other data structures and will be generated as a raw string. This
# method should be used, if you want to convert raw strings to JSON
# instead of UTF-8 strings, e. g. binary data.
def to_json_raw_object
def to_json_raw_object # :nodoc:
{
JSON.create_id => self.class.name,
"raw" => unpack("C*"),
}
end

# call-seq: to_json_raw(*args)
# call-seq:
# to_json_raw -> new_string
#
# This method creates a JSON text from the result of a call to
# to_json_raw_object of this String.
# Returns a specially formatted \JSON string, constructed from +self+;
# see {Binary String As JSON}[rdoc-ref:String@Binary+String+As+JSON].
def to_json_raw(...)
to_json_raw_object.to_json(...)
end
Expand Down
Loading