保留从Ruby中的文件加载YAML的键顺序 [英] Preserve key order loading YAML from a file in Ruby

查看:123
本文介绍了保留从Ruby中的文件加载YAML的键顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保留从磁盘加载,以某种方式处理并写回到磁盘的YAML文件中的键顺序.

I want to preserve the order of the keys in a YAML file loaded from disk, processed in some way and written back to disk.

这是在Ruby(v1.8.7)中加载YAML的基本示例:

Here is a basic example of loading YAML in Ruby (v1.8.7):

require 'yaml'

configuration = nil
File.open('configuration.yaml', 'r') do |file|
  configuration = YAML::load(file)
  # at this point configuration is a hash with keys in an undefined order
end

# process configuration in some way

File.open('output.yaml', 'w+') do |file|
  YAML::dump(configuration, file)
end

不幸的是,一旦建立散列,这将破坏configuration.yaml中键的顺序.我找不到控制YAML::load()使用哪种数据结构的方法,例如阿里巴巴的orderedmap.

Unfortunately, this will destroy the order of the keys in configuration.yaml once the hash is built. I cannot find a way of controlling what data structure is used by YAML::load(), e.g. alib's orderedmap.

我没有运气在网上寻找解决方案.

I've had no luck searching the web for a solution.

推荐答案

如果出于任何原因(例如我)一直使用1.8.7,我会使用active_support/ordered_hash.我知道activesupport似乎是一个很大的包含,但是他们已经在以后的版本中对其进行了重构,使您几乎只需要文件中需要的部分,其余部分就被排除在外了.只需gem install activesupport,并如下所示包含它即可.同样,在您的YAML文件中,请确保使用!! omap声明(和哈希数组).时间示例!

If you're stuck using 1.8.7 for whatever reason (like I am), I've resorted to using active_support/ordered_hash. I know activesupport seems like a big include, but they've refactored it in later versions to where you pretty much only require the part you need in the file and the rest gets left out. Just gem install activesupport, and include it as shown below. Also, in your YAML file, be sure to use an !!omap declaration (and an array of Hashes). Example time!

# config.yml #

months: !!omap
  - january: enero
  - february: febrero
  - march: marzo
  - april: abril
  - may: mayo

这就是它背后的Ruby的样子.

Here's what the Ruby behind it looks like.

# loader.rb #

require 'yaml'
require 'active_support/ordered_hash'

# Load up the file into a Hash
config = File.open('config.yml','r') { |f| YAML::load f }

# So long as you specified an !!omap, this is actually a
# YAML::PrivateClass, an array of Hashes
puts config['months'].class

# Parse through its value attribute, stick results in an OrderedHash,
# and reassign it to our hash
ordered = ActiveSupport::OrderedHash.new
config['months'].value.each { |m| ordered[m.keys.first] = m.values.first }
config['months'] = ordered

我正在寻找一种解决方案,使我可以递归地挖掘从.yml文件加载的Hash,查找那些YAML::PrivateClass对象,然后将它们转换为ActiveSupport::OrderedHash.我可能会问一个问题.

I'm looking for a solution that allows me to recursively dig through a Hash loaded from a .yml file, look for those YAML::PrivateClass objects, and convert them into an ActiveSupport::OrderedHash. I may post a question on that.

这篇关于保留从Ruby中的文件加载YAML的键顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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