From 02a0c7c2dcd3b204249335784edb23a3135f529f Mon Sep 17 00:00:00 2001 From: Kyle Banker Date: Tue, 24 Aug 2010 14:01:24 -0400 Subject: [PATCH] RUBY-165 raise error if BSON.serialize is passed something other than a hash --- ext/cbson/cbson.c | 6 +++++- lib/bson/bson_ruby.rb | 1 + test/mongo_bson/bson_test.rb | 14 ++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/ext/cbson/cbson.c b/ext/cbson/cbson.c index e844c4f..cd54e79 100644 --- a/ext/cbson/cbson.c +++ b/ext/cbson/cbson.c @@ -562,8 +562,12 @@ static void write_doc(buffer_t buffer, VALUE hash, VALUE check_keys, VALUE move_ write_function(key, value, pack_extra(buffer, check_keys)); } - } else { + } else if (strcmp(rb_obj_classname(hash), "Hash") == 0) { rb_hash_foreach(hash, write_function, pack_extra(buffer, check_keys)); + } else { + buffer_free(buffer); + char* cls = rb_obj_classname(hash); + rb_raise(InvalidDocument, "BSON.serialize takes a Hash but got a %s", cls); } // write null byte and fill in length diff --git a/lib/bson/bson_ruby.rb b/lib/bson/bson_ruby.rb index 4bf1fe9..3544d0f 100644 --- a/lib/bson/bson_ruby.rb +++ b/lib/bson/bson_ruby.rb @@ -89,6 +89,7 @@ module BSON end def serialize(obj, check_keys=false, move_id=false) + raise(InvalidDocument, "BSON.serialize takes a Hash but got a #{obj.class}") unless obj.is_a?(Hash) raise "Document is null" unless obj @buf.rewind diff --git a/test/mongo_bson/bson_test.rb b/test/mongo_bson/bson_test.rb index 4933281..552e351 100644 --- a/test/mongo_bson/bson_test.rb +++ b/test/mongo_bson/bson_test.rb @@ -22,6 +22,20 @@ class BSONTest < Test::Unit::TestCase include BSON + def test_require_hash + assert_raise_error InvalidDocument, "takes a Hash" do + BSON.serialize('foo') + end + + assert_raise_error InvalidDocument, "takes a Hash" do + BSON.serialize(Object.new) + end + + assert_raise_error InvalidDocument, "takes a Hash" do + BSON.serialize(Set.new) + end + end + def test_read_bson_io_document doc = {'doc' => 'hello, world'} bson = BSON.serialize(doc)