class Utterson::HtmlCheck

Attributes

errors[R]

Public Class Methods

new(opts={}) click to toggle source
# File lib/utterson/html_check.rb, line 14
def initialize(opts={})
  @file = opts[:file]
  @root = opts[:root]
  @errors = {}
end

Public Instance Methods

add_error(file, url, response) click to toggle source
# File lib/utterson/html_check.rb, line 93
def add_error(file, url, response)
  @errors[file] = {} if @errors[file].nil?
  @errors[file][url] = response
end
check_local_uri(url, file) click to toggle source
# File lib/utterson/html_check.rb, line 83
def check_local_uri(url, file)
  url.gsub!(/\?.*$/, '')
  if url =~ /^\//
    path = File.expand_path(".#{url}", @root)
  else
    path = File.expand_path(url, File.dirname(file))
  end
  add_error(file, url, "File not found") unless File.exists? path
end
check_remote_uri(url, file) click to toggle source
# File lib/utterson/html_check.rb, line 63
def check_remote_uri(url, file)
  begin
    uri = URI(url.gsub(/^\/\//, 'http://'))
  rescue URI::InvalidURIError => e
    return add_error(file, uri.to_s, e.message)
  end
  begin
    response = Net::HTTP.start(uri.host, uri.port,
                               :use_ssl => uri.scheme == 'https') do |http|
      p = uri.path.empty? ? "/" : uri.path
      http.head(p)
    end
    if response.code =~ /^[^23]/
      add_error(file, uri.to_s, response)
    end
  rescue => e
    add_error(file, uri.to_s, e.message)
  end
end
check_uri(url, file) click to toggle source
# File lib/utterson/html_check.rb, line 47
def check_uri(url, file)
  @@semaphore.synchronize do
    if @@checked_urls[url]
      return
    else
      @@checked_urls[url] = true
    end
  end

  if url =~ /^(https?:)?\/\//
    check_remote_uri url, file
  else
    check_local_uri url, file
  end
end
collect_uris_from(f) click to toggle source
# File lib/utterson/html_check.rb, line 37
def collect_uris_from(f)
  ret = []
  doc = Nokogiri::HTML(File.read(f))
  doc.traverse do |el|
    ret << el['src'] unless el['src'].nil?
    ret << el['href'] unless el['href'].nil?
  end
  ret
end
run() click to toggle source
# File lib/utterson/html_check.rb, line 24
def run
  Thread.new do
    collect_uris_from(@file).each do |u|
      check_uri(u, @file)
    end
    unless @result_handler.nil?
      @@semaphore.synchronize do
        @result_handler.call(errors: @errors, urls: @@checked_urls.count)
      end
    end
  end
end
when_done(&handler) click to toggle source
# File lib/utterson/html_check.rb, line 20
def when_done(&handler)
  @result_handler = handler
end