lib/tjson.rb in tjson-0.1.0 vs lib/tjson.rb in tjson-0.2.0
- old
+ new
@@ -5,15 +5,12 @@
require "json"
require "time"
require "base32"
require "base64"
-require "tjson/array"
-require "tjson/binary"
-require "tjson/generator"
+require "tjson/datatype"
require "tjson/object"
-require "tjson/parser"
# Tagged JSON with Rich Types
module TJSON
# Base class of all TJSON errors
Error = Class.new(StandardError)
@@ -22,10 +19,13 @@
EncodingError = Class.new(Error)
# Failure to parse TJSON document
ParseError = Class.new(Error)
+ # Invalid types
+ TypeError = Class.new(ParseError)
+
# Duplicate object name
DuplicateNameError = Class.new(ParseError)
# Maximum allowed nesting (TODO: use TJSON-specified maximum)
MAX_NESTING = 100
@@ -41,28 +41,30 @@
rescue ::EncodingError => ex
raise TJSON::EncodingError, ex.message, ex.backtrace
end
begin
- ::JSON.parse(
+ object = ::JSON.parse(
utf8_string,
max_nesting: MAX_NESTING,
allow_nan: false,
symbolize_names: false,
create_additions: false,
- object_class: TJSON::Object,
- array_class: TJSON::Array
+ object_class: TJSON::Object
)
rescue ::JSON::ParserError => ex
raise TJSON::ParseError, ex.message, ex.backtrace
end
+
+ raise TJSON::TypeError, "invalid toplevel type: #{object.class}" unless object.is_a?(TJSON::Object)
+ object
end
# Generate TJSON from a Ruby Hash or Array
#
# @param obj [Array, Hash] Ruby Hash or Array to serialize as TJSON
# @return [String] serialized TJSON
def self.generate(obj)
- raise TypeError, "expected Hash or Array, got #{obj.class}" unless obj.is_a?(Hash) || obj.is_a?(Array)
- JSON.generate(TJSON::Generator.generate(obj))
+ raise TypeError, "toplevel type must be a Hash" unless obj.is_a?(Hash)
+ JSON.generate(TJSON::DataType.generate(obj))
end
end