如何在ruby中解析yaml文件?

bn31dyow  于 2021-09-29  发布在  Java
关注(0)|答案(3)|浏览(391)

我想知道如何解析包含以下内容的yaml文件:

--- 
javascripts: 
- fo_global:
  - lazyload-min
  - holla-min

目前我正试图以这种方式解析它:

@custom_asset_packages_yml = (File.exists?("#{RAILS_ROOT}/config/asset_packages.yml") ? YAML.load_file("#{RAILS_ROOT}/config/asset_packages.yml") : nil)
    if !@custom_asset_packages_yml.nil?
      @custom_asset_packages_yml['javascripts'].each{ |js|
        js['fo_global'].each{ |script|
         script
        }
      }
    end

但它似乎不起作用,给了我一个错误,值为零。

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each

如果我尝试这样做,它会输出整个字符串(fo_globallazyload-minholla-min):

if !@custom_asset_packages_yml.nil?
          @custom_asset_packages_yml['javascripts'].each{ |js|
            js['fo_global']
          }
        end
ca1c2owp

ca1c2owp1#

我也有同样的问题,但我也想得到文件的内容(在yaml前端事件之后)。
这是我找到的最好的解决方案:

if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
  self.contents = md.post_match
  self.metadata = YAML.load(md[:metadata])
end

资料来源和讨论:https://practicingruby.com/articles/tricks-for-working-with-text-and-files

vecaoik1

vecaoik12#

下面是我从terminal用来测试yml文件内容的一个命令行:

$ ruby  -r yaml -r pp  -e 'pp YAML.load_file("/Users/za/project/application.yml")'
{"logging"=>
  {"path"=>"/var/logs/",
   "file"=>"TacoCloud.log",
   "level"=>
    {"root"=>"WARN", "org"=>{"springframework"=>{"security"=>"DEBUG"}}}}}
8ulbf1ek

8ulbf1ek3#

也许我遗漏了什么,但是为什么要尝试解析文件呢?为什么不加载yaml并检查生成结果的对象?
如果您的样品yaml在 some.yml ,那么这个:

require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect

给我

{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}

相关问题