zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Unix网络编程中的五种IO模型
    go工具库分析——go-snowflake
    defer
    滑动窗口
    快速幂
    Golang使用注意点
    微服务数据一致性基础认知
    KMP算法
    单调栈和单调队列
    LRU简单学习
  • 原文地址:https://www.cnblogs.com/qinyan20/p/3854074.html
Copyright © 2011-2022 走看看