Skip to content

Commit

Permalink
Adding convenience method for accessing db from a document
Browse files Browse the repository at this point in the history
  • Loading branch information
durran committed Feb 10, 2010
1 parent e5ef353 commit 9f08439
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 11 deletions.
1 change: 1 addition & 0 deletions lib/mongoid/collections/operations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module Operations #:nodoc:
# Mongo:Collection. This is used in delegation.
READ = [
:[],
:db,
:count,
:distinct,
:find,
Expand Down
17 changes: 6 additions & 11 deletions lib/mongoid/document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,16 @@ def self.included(base)
attr_accessor :association_name, :_parent
attr_reader :new_record

delegate :collection, :embedded, :primary_key, :to => "self.class"
delegate :collection, :db, :embedded, :primary_key, :to => "self.class"
end
end

module ClassMethods
# Return the database associated with this class.
def db
collection.db
end

# Returns the collection associated with this +Document+. If the
# document is embedded, there will be no collection associated
# with it.
Expand Down Expand Up @@ -125,8 +130,6 @@ def ==(other)
# Example:
#
# <tt>name.assimilate(person, options)</tt>
#
# Returns: The child +Document+.
def assimilate(parent, options)
parentize(parent, options.name); notify; self
end
Expand Down Expand Up @@ -157,10 +160,6 @@ def identify
# Options:
#
# attrs: The attributes +Hash+ to set up the document with.
#
# Example:
#
# <tt>Person.new(:title => "Mr", :age => 30)</tt>
def initialize(attrs = nil)
@attributes = {}
process(attrs)
Expand Down Expand Up @@ -272,10 +271,6 @@ def to_param
# child: The child +Document+ that sent the notification.
# clear: Will clear out the child's attributes if set to true.
#
# Example:
#
# <tt>person.notify_observers(self)</tt> will cause this method to execute.
#
# This will also cause the observing +Document+ to notify it's parent if
# there is any.
def update(child, clear = false)
Expand Down
7 changes: 7 additions & 0 deletions spec/integration/mongoid/document_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@
Person.delete_all
end

describe "#db" do

it "returns the mongo database" do
Person.db.should == Mongoid.master
end
end

context "when document contains a hash field" do

before do
Expand Down
12 changes: 12 additions & 0 deletions spec/unit/mongoid/document_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,18 @@

end

describe ".db" do

before do
@db = stub
@collection.expects(:db).returns(@db)
end

it "returns the database from the collection" do
Person.db.should == @db
end
end

describe "#clone" do

before do
Expand Down

0 comments on commit 9f08439

Please sign in to comment.