Class: Goldencobra::LinkChecker

Inherits:
Object
  • Object
show all
Defined in:
app/models/goldencobra/link_checker.rb

Instance Method Summary collapse

Constructor Details

#initialize(article) ⇒ LinkChecker

Returns a new instance of LinkChecker.



5
6
7
# File 'app/models/goldencobra/link_checker.rb', line 5

def initialize(article)
  @article = article
end

Instance Method Details

get all links of a page and make a check for response status and time



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'app/models/goldencobra/link_checker.rb', line 10

def set_link_checker
  links_to_check = []
  status_for_links = {}
  doc = Nokogiri::HTML(open(@article.absolute_public_url))
  #find all links and stylesheets
  doc.css('a,link').each do |link|
    if add_link_to_checklist(link, "href").present?
      links_to_check << {"link" => add_link_to_checklist(link, "href"), "pos" => link.path}
    end
  end
  #find all images and javascripts
  doc.css('img,script').each do |link|
    if add_link_to_checklist(link,"src").present?
      links_to_check << {"link" => add_link_to_checklist(link,"src"), "pos" => link.path}
    end
  end
  links_to_check = links_to_check.compact.delete_if{|a| a.blank?}
  links_to_check.each_with_index do |linkpos|
    status_for_links[linkpos["link"]] = {"position" => linkpos["pos"]}
    begin
      start = Time.now
      response = open(linkpos["link"])
      status_for_links[linkpos["link"]]["response_code"] = response.status[0]
      status_for_links[linkpos["link"]]["response_time"] = Time.now - start
    rescue Exception  => e
      status_for_links[linkpos["link"]]["response_code"] = "404"
      status_for_links[linkpos["link"]]["response_error"] = e.to_s
    end
  end
  @article.link_checker = status_for_links
end