diff --git a/lib/mongo/objectid.rb b/lib/mongo/objectid.rb index f5f73be..cbc340c 100644 --- a/lib/mongo/objectid.rb +++ b/lib/mongo/objectid.rb @@ -53,6 +53,18 @@ module XGen @@index_time = Time.new.to_i @@index = 0 + # Given a string representation of an ObjectID, return a new ObjectID + # with that value. + def self.from_string(str) + data = [] + i = str.to_i(16) + while i > 0 + data << (i & 0xff) + i >>= 8 + end + self.new(data.reverse) + end + # +data+ is an array of bytes. If nil, a new id will be generated. # The time +t+ is only used for testing; leave it nil. def initialize(data=nil, t=nil) diff --git a/tests/test_objectid.rb b/tests/test_objectid.rb index 9bc356f..86ba45f 100644 --- a/tests/test_objectid.rb +++ b/tests/test_objectid.rb @@ -65,4 +65,12 @@ class ObjectIDTest < Test::Unit::TestCase assert_equal @o, row['_id'] end + def test_from_string + hex_str = @o.to_s + o2 = ObjectID.from_string(hex_str) + assert_equal hex_str, o2.to_s + assert_equal @o, o2 + assert_equal @o.to_s, o2.to_s + end + end