Class: Yamldiff

Inherits:
Object
  • Object
show all
Defined in:
lib/yamldiff/version.rb,
lib/yamldiff/yamldiff.rb

Constant Summary collapse

VERSION =
"0.0.8"

Class Method Summary collapse

Class Method Details

.compare_hashes(first, second, context = []) ⇒ Object

Iterate through all keys in the first hash, checking each key for

1. existence
2. value class equivalence
3. value type equivalence

in the second hash.

Adapted from stackoverflow.com/a/6274367/91029



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/yamldiff/yamldiff.rb', line 18

def compare_hashes(first, second, context = [])
  errors = []

  first.each do |key, value|
    unless second.key?(key)
      errors << YamldiffKeyError.new(key, context) # "Missing key : #{key} in path #{context.join(".")}"
      next
    end

    value2 = second[key]
    if (value.class != value2.class)
      errors << YamldiffKeyValueTypeError.new(key, context) # "Key value type mismatch : #{key} in path #{context.join(".")}"
      next
    end

    if value.is_a?(Hash)
      errors << compare_hashes(value, second[key], context + [key])
      next
    end

    if (value != value2)
      errors << YamldiffKeyValueError.new(key, context) # "Key value mismatch : #{key} in path #{context.join(".")}"
    end
  end

  errors.flatten
end

.diff_yaml(first, second, errors_for = {}) ⇒ Object

Compare the two yaml files



4
5
6
7
8
9
# File 'lib/yamldiff/yamldiff.rb', line 4

def diff_yaml(first, second, errors_for = {})
  primary            = YAML.load(File.open(first))
  secondary          = YAML.load(File.open(second))
  errors_for[second] = compare_hashes(primary, secondary)
  errors_for
end