allow [] on DB, Collection instances to get collections/sub-collections

This commit is contained in:
Mike Dirolf 2009-08-17 11:11:03 -04:00
parent 8a6c9635d7
commit 047fc60c91
3 changed files with 26 additions and 0 deletions

View File

@ -48,6 +48,17 @@ module XGen
@hint = nil
end
# Get a sub-collection of this collection by name.
#
# Raises InvalidName if an invalid collection name is used.
#
# :name :: the name of the collection to get
def [](name)
name = "#{self.name}.#{name}"
return Collection.new(self, name) if !db.strict? || db.collection_names.include?(name)
raise "Collection #{name} doesn't exist. Currently in strict mode."
end
# Set hint fields to use and return +self+. hint may be a single field
# name, array of field names, or a hash (preferably an OrderedHash).
# May be +nil+.

View File

@ -246,6 +246,7 @@ module XGen
return Collection.new(self, name) if !strict? || collection_names.include?(name)
raise "Collection #{name} doesn't exist. Currently in strict mode."
end
alias_method :[], :collection
# Drop collection +name+. Returns +true+ on success or if the
# collection does not exist, +false+ otherwise.

View File

@ -31,6 +31,20 @@ class TestCollection < Test::Unit::TestCase
@@test.drop()
end
def test_collection
assert_raise InvalidName do
@@db["te$t"]
end
assert_kind_of Collection, @@db["test"]
assert_equal @@db["test"].name(), @@db.collection("test").name()
assert_equal @@db["test"].name(), @@db[:test].name()
assert_kind_of Collection, @@db["test"]["foo"]
assert_equal @@db["test"]["foo"].name(), @@db.collection("test.foo").name()
assert_equal @@db["test"]["foo"].name(), @@db["test.foo"].name()
end
def test_safe_insert
a = {"hello" => "world"}
@@test.insert(a)