From 8f2e25f8d3905b8c0d4bf82bd47147993d0fd902 Mon Sep 17 00:00:00 2001 From: Kyle Banker Date: Tue, 8 Dec 2009 17:13:54 -0500 Subject: [PATCH] added custom exception for illegal object ids --- README.rdoc | 2 +- lib/mongo/errors.rb | 3 +++ lib/mongo/types/objectid.rb | 4 ++-- test/test_objectid.rb | 12 ++++++++++++ 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/README.rdoc b/README.rdoc index 669bafa..be4e332 100644 --- a/README.rdoc +++ b/README.rdoc @@ -329,7 +329,7 @@ See HISTORY. = Credits -See CREDITS +See CREDITS. = License diff --git a/lib/mongo/errors.rb b/lib/mongo/errors.rb index e328d6c..a8b4260 100644 --- a/lib/mongo/errors.rb +++ b/lib/mongo/errors.rb @@ -30,6 +30,9 @@ module Mongo # Raised when given a string is not valid utf-8 (Ruby 1.8 only). class InvalidStringEncoding < MongoRubyError; end + # Raised when attempting to initialize an invalid ObjectID. + class InvalidObjectID < MongoRubyError; end + # Raised on failures in connection to the database server. class ConnectionError < MongoRubyError; end diff --git a/lib/mongo/types/objectid.rb b/lib/mongo/types/objectid.rb index 90b167e..98fe375 100644 --- a/lib/mongo/types/objectid.rb +++ b/lib/mongo/types/objectid.rb @@ -70,7 +70,7 @@ module Mongo # Given a string representation of an ObjectID, return a new ObjectID # with that value. def self.from_string(str) - raise "illegal ObjectID format" unless legal?(str) + raise InvalidObjectID, "illegal ObjectID format" unless legal?(str) data = [] 12.times do |i| data[i] = str[i * 2, 2].to_i(16) @@ -83,7 +83,7 @@ module Mongo # removed. If you are not sure that you need this method you should be # using the regular from_string. def self.from_string_legacy(str) - raise "illegal ObjectID format" unless legal?(str) + raise InvalidObjectID, "illegal ObjectID format" unless legal?(str) data = [] BYTE_ORDER.each_with_index { |string_position, data_index| data[data_index] = str[string_position * 2, 2].to_i(16) diff --git a/test/test_objectid.rb b/test/test_objectid.rb index 8b19921..0d37a73 100644 --- a/test/test_objectid.rb +++ b/test/test_objectid.rb @@ -79,6 +79,12 @@ class ObjectIDTest < Test::Unit::TestCase assert_equal @o.to_s, o2.to_s end + def test_illegal_from_string + assert_raise InvalidObjectID do + ObjectID.from_string("") + end + end + def test_from_string_legacy hex_str = @o.to_s_legacy o2 = ObjectID.from_string_legacy(hex_str) @@ -87,6 +93,12 @@ class ObjectIDTest < Test::Unit::TestCase assert_equal @o.to_s, o2.to_s end + def test_illegal_from_string_legacy + assert_raise InvalidObjectID do + ObjectID.from_string_legacy("") + end + end + def test_legal assert !ObjectID.legal?(nil) assert !ObjectID.legal?("fred")