Class: DatabaseProxy

Inherits:
Object show all
Defined in:
lib/mongoid/database_proxy.rb

Overview

Proxy that enables runtime swapping of a MongoDB database, as it appears to be cached at several points within Mongoid.

This proxy is generated by the ConnectionProxy when asked for a specific database.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection, name) ⇒ DatabaseProxy

Set our default connection and name.



42
43
44
45
# File 'lib/mongoid/database_proxy.rb', line 42

def initialize(connection, name)
    @connection = connection
    switch(name)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object

Proxy methods to the correct database.



94
95
96
# File 'lib/mongoid/database_proxy.rb', line 94

def method_missing(*args, &block)
    target.send(*args, &block)
end

Class Method Details

.mutexObject

Global mutex… for great thread safety!



35
36
37
# File 'lib/mongoid/database_proxy.rb', line 35

def DatabaseProxy.mutex
    @mutex
end

.poolObject

Accessor for class-level instance variable that holds all the connection-database pairs that we know about, so that we can switch all of them globally.



28
29
30
# File 'lib/mongoid/database_proxy.rb', line 28

def DatabaseProxy.pool
    @pool
end

Instance Method Details

#create_collection(name, opts) ⇒ Object

Create a proxied collection.



87
88
89
# File 'lib/mongoid/database_proxy.rb', line 87

def create_collection(name, opts)
    CollectionProxy.new(self, name, opts)
end

#reset!Object

Resets back to the default database connections.



73
74
75
# File 'lib/mongoid/database_proxy.rb', line 73

def reset!
    synchronize { Thread.current[:mongo_database] = nil }
end

#switch(name) ⇒ Object

Switch to a different database on the same connection.



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/mongoid/database_proxy.rb', line 57

def switch(name)
    synchronize do
        # Connect to the cached database if available.
        pool = (DatabaseProxy.pool[@connection] ||= {})
        database = (pool[name] || (pool[name] = @connection.db(name)))

        # Set the default if we haven't, and away we go (for this
        # thread only).
        @default ||= database 
        Thread.current[:mongo_database] = database
    end
end

#synchronize(&block) ⇒ Object

Convenience method for synchronizing threads.



50
51
52
# File 'lib/mongoid/database_proxy.rb', line 50

def synchronize(&block)
    DatabaseProxy.mutex.synchronize(&block)
end

#targetObject

Returns the raw Mongo::DB object.



80
81
82
# File 'lib/mongoid/database_proxy.rb', line 80

def target
    synchronize { Thread.current[:mongo_database] || @default }
end