Class: JsonChecker::JSONFetcher

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

Class Method Summary collapse

Class Method Details

.fetch_response(response) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/json_checker/json_fetcher.rb', line 43

def self.fetch_response(response)
  case response
    when Net::HTTPSuccess then
      return JSONFetcher.json_from_content(response.body)
    else
      puts"[ERROR] Connection error"
  end
end

.json_from_content(content) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/json_checker/json_fetcher.rb', line 30

def self.json_from_content(content)
  if content.nil? || (!content.is_a?(String) && (!content.is_a?(Hash)))
    return nil
  end

  begin
    return content.is_a?(String) ? JSON.parse(content) : JSON.parse(content.to_json)
  rescue JSON::ParserError => e
    puts "[ERROR] Invalid json"
  end
  return nil
end

.json_from_path(path) ⇒ Object



8
9
10
11
12
13
14
15
16
17
# File 'lib/json_checker/json_fetcher.rb', line 8

def self.json_from_path(path)
  begin
    jsonFile = open(path)
    jsonContent = jsonFile.read
    return JSONFetcher.json_from_content(jsonContent)
  rescue
    puts "[ERROR] #{path} not found"
    return nil
  end
end

.json_from_url(url) ⇒ Object



19
20
21
22
23
24
25
26
27
28
# File 'lib/json_checker/json_fetcher.rb', line 19

def self.json_from_url(url)
  begin
    uri = URI(url)
    response = Net::HTTP.get_response(uri)
    return JSONFetcher.fetch_response(response)  
  rescue
  end
  
  return nil
end