Rails:yml 合并
假设我有一个用于 Rails 配置的 yml 文件...
settings.yml
defaults: &defaults
interceptor_email: [email protected]
development:
<<: *defaults
test:
<<: *defaults
production:
<<: *defaults
并且我想要另一个 yml 文件,该文件不包含在每个开发人员在本地维护的版本控制中...
user_settings .yml
development:
interceptor_email: [email protected]
如何合并这些键?我正在使用 esb 处理 yml 文件,所以这也是一个选项。只是不知道该怎么做。我已经设置了它,因此如果我的环境缺少密钥,密钥会回退到默认值。
Say I have a yml file for my rails configuration...
settings.yml
defaults: &defaults
interceptor_email: [email protected]
development:
<<: *defaults
test:
<<: *defaults
production:
<<: *defaults
and I want to have another yml file that is NOT included in version control that each developer maintains locally...
user_settings.yml
development:
interceptor_email: [email protected]
How can I merge these keys? I am processing my yml files with esb, so that is also an option. Just having trouble figuring out how to do it. I have it setup so keys fallback to the defaults if a key is missing for my environments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不能分别读取两个yml文件吗?
现在您应该拥有设置的哈希值,然后您可以根据需要合并哈希值。如果第二个哈希值与第一个哈希值具有相同的密钥,则第一个哈希值将被覆盖。
Can't you read the two yml files separately?
Now you should have the hash value of the settings, then you can merge the hash if you want. If the second hash has the same key as the first hash, the first one will be overwritten.
这就是我这样做的方式(免责声明,我刚刚写了它,所以它还没有单元测试等...我会在改进时更新它):
你可以这样称呼它:
如果你愿意仔细想想,这里还有很大的改进空间。理想情况下,使“Config”成为不处理文件的接口,并在
YamlConfig
、IniConfig
、CliConfig
、DbConfig
中实现代码>,<代码>CookieConfig。这样,如果有一天您决定新的配置格式超级种子 yaml 非常酷,您可以轻松更改它而不会破坏任何内容。您可以让命令行配置选项轻松覆盖来自配置文件的选项。您可以为任何 ruby 项目重用配置模块,无论配置值来自何处。或者也许只是停止发明热水。快速浏览让我觉得那里有一些非常热水...接下来编写一些文档、单元测试、输入验证、错误处理并为配置值创建一些奇特的读/写访问器。也许您希望能够请求这样的配置值,而不是一直编写数组和哈希:
This is how I do it (disclaimer, I just wrote it, so it doesn't have unit tests yet etc...I'll update this as I improve on it):
You can call it like this:
And if you want to go fancy, there's a lot of room for improvement here. Ideally make ´Config´ an interface that does not deal with files, and implement in
YamlConfig
,IniConfig
,CliConfig
,DbConfig
,CookieConfig
. That way if you decide one day the that that new config format super seeding yaml is so cool, you can easily change it without breaking anything. And you can have the command line configuration options easily override the ones coming from the configuration files. And you can reuse the config module for any ruby project regardless of where the config values come from. Or maybe just stop inventing hot water. A quick browse makes me think there's some pretty hot water over there...Next write some documentation, unit tests, input validation, error handling and create some fancy read/write accessors for the config values. Maybe you'd like to be able to ask for a config value like this instead of writing arrays and hashes all the time: