Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-1410

runtime configuration problem

    • Type: Icon: Task Task
    • Resolution: Done
    • 12_01_17
    • Affects Version/s: None
    • Component/s: None

      I need an ability to set connection settings for model at runtime.

      Unable to find source-code formatter for language: set_database```. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
       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've 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?

            Assignee:
            Unassigned Unassigned
            Reporter:
            sigerello sigerello
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: