mongoid/mongoid — Issue #1409: runtime configuration problem
Author: sigerello
Created: 2011-11-03 20:56:38+00:00
State: open

I need an ability to set connection settings for model at runtime.
```set_database``` method is not useful for me because I have a lot of different (dynamic) connection settings and can't store all of them in ```mongoid.yml``` file.

I added this code to my initializer:

module Mongoid::Collections
module ClassMethods
def on(options = {})
options.symbolize_keys!
conn = Mongo::Connection.new(options[:host], options[:port])
db = conn[options[:database]]
auth = db.authenticate(options[:username], options[:password])
self._collection = Mongoid::Collections::Master.new(db, self.collection_name)
self
end
end
end

I have simple user model like this (nothing special here):

class User
include Mongoid::Document
include Mongoid::Timestamps
field :name, :type => String
field :age, :type => Integer
end

And there is my controller:

class UsersController < ApplicationController
def index
# options look like this but actually I get them dynamically using other methods
connection_options = { :host => 'example.com', :port => 10074, :username => 'user', :password => 'pass', :database => 'dbname' }
@users = User.on(connection_options).order_by([:created_at, :desc]).all
end
end

It works fine except one problem – @users is array of ```BSON::OrderedHash``` instances insted of ```User``` instances.
So for some reason it not instantiates objects after my patch.

My system is:

ruby-1.9.2-p290
rails 3.1.1
mongoid 2.3.2
mongo 1.4.0
bson 1.4.0
bson_ext 1.4.0

Am I doing something wrong or missing something?
Is there are better/simpler solution to set connection settings for model at runtime?