mongoid yaml 结合主机的环境变量

mongoid yaml combines environment variables for hosts

我是 rails 和 mongoid 的新手,我有 mongoid.yml 包含以下条目的文件:

development:
  # Configure available database clients. (required)
  clients:
    # Defines the default client. (required)
    default:
      # Defines the name of the default database that Mongoid can connect to.
      # (required).
      database: mycollectionname
      # Provides the hosts the default client can connect to. Must be an array
      # of host:port pairs. (required)
      hosts:
        - localhost:27017

这适用于开发,但是,在生产中,我想从环境变量中指定主机,例如 ENV['OPENSHIFT_MONGODB_DB_HOST'] + ":" + ENV['OPENSHIFT_MONGODB_DB_PORT']

我试过各种方法,比如这个

    hosts:
      - <%= \"#{ENV['OPENSHIFT_MONGODB_HOST']}:#{ENV['OPENSHIFT_MONGODB_PORT']}\" %>

    hosts:
      - #{ENV['OPENSHIFT_MONGODB_HOST']:ENV['OPENSHIFT_MONGODB_PORT']}

等,但 none 有效

在yaml代码中,<%= %>是让你插入ruby代码,你可以在里面使用Expression Substitution来格式化你的url

Expression substitution is a means of embedding the value of any Ruby expression into a string using #{ and }

像这样可以做到:

<%= "#{ENV['OPENSHIFT_MONGODB_HOST']}:#{ENV['OPENSHIFT_MONGODB_PORT']}" %>

在我使用 openshift 的 mongoid 项目中,我使用它的 uri: 字段是这样的:

uri: <%= "#{ENV['OPENSHIFT_MONGODB_DB_URL']}#{ENV['OPENSHIFT_APP_NAME']}" %>

也请注意缩进,一定要准确,一定要space! Tab 也会出问题!