Module: SycLink::LinkChecker

Included in:
Link
Defined in:
lib/syclink/link_checker.rb

Overview

Methods to check links for availability. A link may be an URI or a file

Instance Method Summary collapse

Instance Method Details

#responseObject

Checks whether a link is reachable. If so code ‘200’ is returned otherwise ‘Error’ #response expects that the including class has an attribute ‘url’



12
13
14
15
16
# File 'lib/syclink/link_checker.rb', line 12

def response
  return "Error" unless url
  uri = to_uri(url)
  uri ? response_of_uri(uri) : response_of_file(url)
end

#response_of_file(file) ⇒ Object

Checks whether a file exists. If so it returns ‘200’ otherwise ‘error’



32
33
34
# File 'lib/syclink/link_checker.rb', line 32

def response_of_file(file)
  File.exists?(file) ? "200" : "Error"
end

#response_of_uri(uri) ⇒ Object

Checks whether the uri is reachable. If so it returns ‘200’ otherwise ‘Error’. uri has to have a host, that is uri.host should not be nil



20
21
22
23
24
25
26
27
28
# File 'lib/syclink/link_checker.rb', line 20

def response_of_uri(uri)
  begin
    Net::HTTP.start(uri.host, uri.port) do |http|
      http.head(uri.path.size > 0 ? uri.path : "/").code
    end
  rescue Exception => e
    "Error"
  end
end

#to_uri(url) ⇒ Object

Transforms an URL (String) to an URI. If URL is not valid false is returned



38
39
40
41
42
43
44
45
# File 'lib/syclink/link_checker.rb', line 38

def to_uri(url)
  uri = URI.parse(url)
  uri.host.nil? ? false : uri
rescue URI::BadURIError
  false
rescue URI::InvalidURIError
  false
end