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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值