Class: LinkChecker

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

Overview

Checks whether URL is accessible, following up to 10 redirects. Example:

LinkChecker.new('http://example.com').accessible?

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Constructor Details

#initialize(uri_str, limit = 10) ⇒ LinkChecker

Returns a new instance of LinkChecker.



8
9
10
11
# File 'lib/link_checker.rb', line 8

def initialize(uri_str, limit = 10)
  @uri_str, @limit = uri_str, limit
  @uri_str = "http://#{@uri_str}" unless @uri_str.include?('://')
end

Instance Method Details

#accessible?Boolean

Returns:

  • (Boolean)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/link_checker.rb', line 13

def accessible?
  return false if @limit == 0
  uri = URI(@uri_str)
  Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|
    request = Net::HTTP::Get.new(uri.request_uri)
    response = http.request(request)
    case response
    when Net::HTTPNotFound  then false
    when Net::HTTPSuccess   then true
    when Net::HTTPRedirection
      location = response['location']
      unless location.include?('://')
        host_with_protocol = @uri_str[/^[^\:]+\:\/\/[^\/]+/, 0]
        location = host_with_protocol + location
      end
      self.class.new(location, @limit - 1).accessible?
    else
      false
    end
  end
end