Class: JsonChecker::JSONComparator

Inherits:
Object
  • Object
show all
Defined in:
lib/json_checker/json_comparator.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.compare(fileToCheck, compareTo) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/json_checker/json_comparator.rb', line 8

def self.compare(fileToCheck, compareTo)
  
  if fileToCheck.nil? || compareTo.nil? || !compareTo.is_a?(Array) || !fileToCheck.is_a?(JSONToCheck)
    return
  end

  compareTo.each do |compare|
    if CheckableFile.is_valid_representation?(compare)
      checkableFile = CheckableFile.new(compare)
      fileContent = checkableFile.get_content()

      jsonComparator = JSONComparator.new()
      jsonComparator.compare_json("Comparing #{fileToCheck.name} with #{checkableFile.name}", fileToCheck.get_content(), fileContent)
    end
  end
end

Instance Method Details

#add_line(line) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/json_checker/json_comparator.rb', line 62

def add_line(line)
  
  if line.nil?
    return ""
  end 

  line = line.gsub("\n","")
  formatter = "<p class=\"%{first}\">%{second}</p>"
  className = "null"

  if line.chars.first == "+"
    className = "addition"
  elsif line.chars.first == "-"
    className = "remotion"
  end
  return formatter % {first: className, second: line}
end

#compare_json(title, json, jsonToCompare) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/json_checker/json_comparator.rb', line 25

def compare_json(title, json, jsonToCompare)    
  temp_json = tempfile_from_json(json)
  temp_jsonToCompare = tempfile_from_json(jsonToCompare)

  unless temp_json.nil? && temp_jsonToCompare.nil?
    diff = Diffy::Diff.new(temp_jsonToCompare.path, temp_json.path, :source => 'files', :context => 3)
    html_report_from_diff(title, diff)

    temp_jsonToCompare.delete
    temp_json.delete
  end
end

#html_report_from_diff(title, diff) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/json_checker/json_comparator.rb', line 50

def html_report_from_diff(title, diff)
  if diff.nil?
    return nil
  end

  result = ""
  diff.to_s.each_line do |line|
    result = result + add_line(line)
  end
  HTMLOutput.add_comparation_item(title, result)
end

#tempfile_from_json(json) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/json_checker/json_comparator.rb', line 38

def tempfile_from_json(json)
  json = JSONFetcher.json_from_content(json)
  unless json.nil?
    tempfile = Tempfile.new("temp_json")
    tempfile.write(JSON.pretty_generate(json) + "\n")
    tempfile.close
    return tempfile
  end
  puts "[ERROR] File content is not a valid JSON"
  return nil
end