ruby-on-rails - 是否有内置函数来访问嵌套的 yaml 字符串?

标签 ruby-on-rails ruby yaml

假设我们有以下 YAML 结构:

books:
  book_one: "Some name"
  book_two: "Some other name"

如果我们像这样加载文件:

f = YAML.load_file("my.yml")

我们可以像这样访问 book_one:f["books"]["book_one"]。是否有内置函数可以接受如下字符串:books.book_one 并返回相同的值?

编辑:这是我目前所拥有的,而且似乎有效:

  ...
  @yfile = YAML.load_file("my.yml")
  ...


  def strings_for(key)
    key_components = key.split(".")
    container      = @yfile
    key_components.each_with_index do |kc,idx|
      if container && container.kind_of?(Hash) && container.keys.include?(kc)
        container  = container[kc]
      else
        container = nil
      end
    end
    container
  end

最佳答案

您可以使用 OpenStruct以及为此的递归函数,它看起来像这样:

require 'ostruct'

def deep_open_struct(hash)
  internal_hashes = {}
  hash.each do |key,value|
    if value.kind_of?( Hash )
      internal_hashes[key] = value
    end
  end
  if internal_hashes.empty?
    OpenStruct.new(hash)
  else
    duplicate = hash.dup
    internal_hashes.each do |key,value|
      duplicate[key] = deep_open_struct(value)
    end
    OpenStruct.new(duplicate)
  end
end

f = YAML.load_file('my.yml')
struct = deep_open_struct(f)
puts struct.books.book_one

关于ruby-on-rails - 是否有内置函数来访问嵌套的 yaml 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11137518/

相关文章:

javascript - Angular + rails : Delete posts

ruby-on-rails - 调用没有 ID 的新方法的路由问题

ruby - 有人可以解释这个 ruby 代码吗?

ruby-on-rails - 未初始化的常量 ThinkingSphinx::Deltas::DelayedDelta

ruby-on-rails - Devise Rails 4 中令人难忘的

ruby-on-rails - Rails URL 问题

yaml - yaml 文件中的条件是否可行?

parsing - 使用 YAML.mapping 解析复杂的 YAML 结构

windows - 如何更改 stack.yaml 在 Windows 上的默认位置?

ruby-on-rails - 如何使用 Rails/ActiveRecord 将 postgreSQL 中的主键类型更改为 bigserial