4

my goal:

  • check if yaml document include value for specific key using ypath/xpath
  • select value for specified key using ypath/xpath
  • document yaml:

    app:
        name: xxx
        version: xxx
    description:
        author:
            name: xxx
            surname: xxx
            email: xxx@xxx.xx
    

    what was checked:*

  • google
  • stackoverflow
  • Ruby API (YAML::DBM as one of methods it provide is select)
  • example:

    Module::Class.select('description/author/name')
    Module::Class.select('*/name')
    Module::Class.isset?('*/name')
    
    xyz
    • 2,277
    • 2
    • 25
    • 41

    2 Answers2

    1

    Use yaml:

    require 'yaml'
    yml = YAML.load_file('your_file.yml')
    

    Now yml is a hash. You can use it like one. Here is a simple and ugly solution for what you try:

    if !yml["description"].nil? && !yml["description"]["author"].nil? && !yml["description"]["author"]["name"].nil? && !yml["description"]["author"]["name"].empty?
      puts "An author is set!"
    end
    
    Ivaylo Strandjev
    • 69,226
    • 18
    • 123
    • 176
    • Hello, thx for response, but it's not what i meant, I've updated My Goal section in question. BR. – xyz Feb 12 '13 at 10:08
    • Sorry link to the wrong answer. Take a look here: http://stackoverflow.com/a/9977987/812912 – Ivaylo Strandjev Feb 12 '13 at 10:10
    • Yeap i saw that also, but problem is that there is no example attached in that pdf. – xyz Feb 12 '13 at 10:13
    • have you seen the rdoc the user refers to? – Ivaylo Strandjev Feb 12 '13 at 10:14
    • Of course, but unfortunately it is not well documented in manner of example (working thing). Unless somebody already worked with ypath in Ruby YAML i will have to dig more and try to find proper way... but i would rather not invent wheel from beginning :) – xyz Feb 12 '13 at 10:18
    0

    Since there are no up-to-date YPath implementations around, I would suggest to give a chance ActiveSupport and Nokogiri:

    yml = LOAD_YML_WITH_YOUR_PREFERRED_YAML_ENGINE
    
    # ActiveSupport adds a to_xml method to Hash
    xml = yml.to_xml(:root => 'yaml')
    
    doc = Nokogiri::XML(xml)
    doc.xpath("description/author/name").map do |name|
      puts [name['key'], name['value']]
    end
    
    Aleksei Matiushkin
    • 119,336
    • 10
    • 100
    • 160
    • Yeap, w can't use YPath. I've tried to use YAML/Psych::DBM without luck. I've ended using XML instead of YAML with Nokogiri gem. Thx. – xyz Feb 13 '13 at 09:02