Mongoid Without Rails

question

I'm playing with a standalone ruby application and can't configure Mongoid 3.0.13 to work.

I've run across a couple example apps that have configuration blocks like:

Mongoid::Config.instance.from_hash({"database" => "oid"})

Or

Mongoid.configure do |config|
 name = "mongoid_test_db"
 host = "localhost"
 port = 27017
 config.database = Mongo::Connection.new.db(name)
end

These result in:

undefined method `database=' for Mongoid::Config:Module (NoMethodError)

It seems the configuration settings have changed recently.

I also tried:

Mongoid::Config.connect_to("sweet")

But that seems to do nothing.

answer1

By "standalone" I'm assuming you mean not rails. Mongoid actually provides and easy to make this work regardless of what you're running it in.

  1. Define a mongoid.yml file with your database connection info in it like normal.
  2. Make sure you've required Mongoid in your application.
  3. Call Mongoid.load! to have Mongoid parse your configuration file and initialize itself.

    require 'mongoid'
    Mongoid.load!('/path/to/your/mongoid.yml')

This info can also be found here under the "Sinatra, Padrino, and others" section: http://mongoid.org/en/mongoid/docs/installation.html

The same approach is applicable for non-webapps. Hope that helps.

answer2

The previous answer is correct to use Mongoid.load! if you want to load from a mongoid config file. I ran into a case where I needed to embed the Mongoid config in another config file. Therefore, I needed a way to load the configuration from a hash.

In >3.1, you will be able to call Mongoid.load_configuration(hash).

Unfortunately, this function is private in 3.0. Therefore, setting up a public alias method before loading Mongoid works:

module Mongoid
  module Config
    def load_configuration_hash(settings)
      load_configuration(settings)
    end
  end
end

Make sure this code gets called before require 'mongoid'. Now you can call Mongoid.load_configuration_hash(hash).

地址: http://stackoverflow.com/questions/15283984/mongoid-without-rails

原文地址:https://www.cnblogs.com/qinyan20/p/3854074.html