How do I parse a YAML file in Ruby?

前端 未结 3 810
时光取名叫无心
时光取名叫无心 2020-11-29 16:01

I would like to know how to parse a YAML file with the following contents:

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

C

相关标签:
3条回答
  • 2020-11-29 16:40

    I had the same problem but also wanted to get the content of the file (after the YAML front-matter).

    This is the best solution I have found:

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

    Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files

    0 讨论(0)
  • 2020-11-29 16:57

    Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

    If your sample YAML is in some.yml, then this:

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

    gives me

    {"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}
    
    0 讨论(0)
  • 2020-11-29 16:57

    Here is the one liner i use, from terminal, to test the content of yml file(s):

    $ 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"}}}}}
    
    0 讨论(0)
提交回复
热议问题