码迷,mamicode.com
首页 > 其他好文 > 详细

Mongoid Without Rails

时间:2014-07-19 15:29:05      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:des   style   http   os   io   for   

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

Mongoid Without Rails,布布扣,bubuko.com

Mongoid Without Rails

标签:des   style   http   os   io   for   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!