How to compare keys in yaml files?

后端 未结 4 953
醉梦人生
醉梦人生 2021-02-14 15:27

There are two ruby on rails internationalization yaml files. One file is complete and another one is with missing keys. How can I compare two yaml files and see missing keys in

4条回答
  •  长发绾君心
    2021-02-14 15:57

    Assuming file1 is the proper version and file2 is the version with missing keys:

    def compare_yaml_hash(cf1, cf2, context = [])
      cf1.each do |key, value|
    
        unless cf2.key?(key)
          puts "Missing key : #{key} in path #{context.join(".")}" 
          next
        end
    
        value2 = cf2[key]
        if (value.class != value2.class)
          puts "Key value type mismatch : #{key} in path #{context.join(".")}" 
          next
        end
    
        if value.is_a?(Hash)
          compare_yaml_hash(value, value2, (context + [key]))  
          next
        end
    
        if (value != value2)
          puts "Key value mismatch : #{key} in path #{context.join(".")}" 
        end    
      end
    end
    

    Now

    compare_yaml_hash(YAML.load_file("file1"), YAML.load_file("file2"))
    

    Limitation: Current implementation should be extended to support arrays if your YAML file contains arrays.

提交回复
热议问题