Question

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')
    
    Was it helpful?

    Solution 2

    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
    

    OTHER TIPS

    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
    
    Licensed under: CC-BY-SA with attribution
    Not affiliated with StackOverflow
    scroll top