在 Rails 中加载 YAML 配置文件时出错 [英] Error when loading YAML config files in Rails

查看:50
本文介绍了在 Rails 中加载 YAML 配置文件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 MongoDB 配置 Rails,在解析 config/mongo.yml 文件时发现一个奇怪的问题.

I am configuring Rails with MongoDB, and find a strange problem when paring config/mongo.yml file.

config/mongo.yml 是通过执行script/rails generate mongo_mapper:config 生成的,如下所示:

config/mongo.yml is generated by executing script/rails generate mongo_mapper:config, and it looks like following:

defaults: &defaults
  host: 127.0.0.1
  port: 27017

development:
  <<: *defaults
  database: tc_web_development

test:
  <<: *defaults
  database: tc_web_test

从配置文件中我们可以看到对象developmenttest 都应该有一个database 字段.但是当它在config/initializers/mongo.db中解析加载时,

From the config file we can see the objects development and test should both have a database field. But when it is parsed and loaded in config/initializers/mongo.db,

config = YAML::load(File.read(Rails.root.join('config/mongo.yml')))
puts config.inspect
MongoMapper.setup(config, Rails.env)

奇怪的事情来了:puts config.inspect的输出是

the strange thing comes: the output of puts config.inspect is

{"defaults"=>{"host"=>"127.0.0.1", "port"=>27017}, "development"=>{"host"=>"127.0.0.1", "port"=>27017}, "test"=>{"host"=>"127.0.0.1", "port"=>27017}}

不包含 database 属性.但是当我在普通的 ruby​​ 控制台中执行相同的语句时,不是使用 rails 控制台,而是以正确的方式解析 mongo.yml.

which does not contain database attribute. But when I execute the same statements in a plain ruby console, instead of using rails console, mongo.yml is parsed in a right way.

{"defaults"=>{"host"=>"127.0.0.1", "port"=>27017}, "development"=>{"host"=>"127.0.0.1", "port"=>27017, "database"=>"tc_web_development"}, "test"=>{"host"=>"127.0.0.1", "port"=>27017, "database"=>"tc_web_test"}}

我想知道这个问题的原因可能是什么.有任何想法吗?谢谢.

I am wondering what may be the cause of this problem. Any ideas? Thanks.

推荐答案

根据您的系统,Ruby 可能在编译时支持 Psych,它取代了旧的 Syck解析器.您所看到的问题(仅涉及使用带有默认值的干"yaml 文件)已在 Psych 中修复,但尚未在发布的 Ruby 版本中修复.

Depending on your system, Ruby may have been compiled with Psych support, which replaces the older Syck parser. The issue you're seeing (which only involves using a "dry" yaml file with the defaults) has already been fixed in Psych, but is not yet in a released Ruby version.

现在,您可以通过将其放在 boot.rb 的末尾来强制 YAML 解析器使用 Syck 而不是 Psych(但要注意——Ruby 的未来版本将不再包含 Syck):

For now, you can either force the YAML parser to use Syck instead of Psych by putting this at the end of your boot.rb (but beware -- a future version of Ruby will no longer include Syck):

YAML::ENGINE.yamler = 'syck'

或者您可以暂时使用非 DRY YAML 文件(没有默认值).

Or you could just use a non-DRY YAML file (without the defaults) for the time being.

这篇关于在 Rails 中加载 YAML 配置文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆