New ObjectID#legal_oid_string. Use that in ObjectID#from_string.

This commit is contained in:
Jim Menard 2009-01-15 11:25:23 -05:00
parent d34108f071
commit 123b2c8d78
3 changed files with 23 additions and 0 deletions

View File

@ -121,6 +121,11 @@ module XGen
@db.drop_index(@name, '*')
end
# Drop the entire collection. USE WITH CAUTION.
def drop
@db.drop_collection(@name)
end
# Return an array of hashes, one for each index. Each hash contains:
#
# :name :: Index name

View File

@ -64,6 +64,7 @@ module XGen
# 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_oid_string(str)
data = []
BYTE_ORDER.each_with_index { |string_position, data_index|
data[data_index] = str[string_position * 2, 2].to_i(16)
@ -71,6 +72,13 @@ module XGen
self.new(data)
end
def self.legal_oid_string(str)
len = BYTE_ORDER.length * 2
str =~ /([0-9a-f]+)/i
match = $1
str && str.length == len && match == str
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)

View File

@ -73,6 +73,16 @@ class ObjectIDTest < Test::Unit::TestCase
assert_equal @o.to_s, o2.to_s
end
def test_legal_oid_string
assert !ObjectID.legal_oid_string(nil)
assert !ObjectID.legal_oid_string("fred")
assert !ObjectID.legal_oid_string("0000")
assert !ObjectID.legal_oid_string('000102030405060708090A0')
assert ObjectID.legal_oid_string('000102030405060708090A0B')
assert ObjectID.legal_oid_string('abcdefABCDEF123456789012')
assert !ObjectID.legal_oid_string('abcdefABCDEF12345678901x')
end
def test_from_string_leading_zeroes
hex_str = '000000000000000000abcdef'
o = ObjectID.from_string(hex_str)