Extending Raakt

Extending Raakt (and other Ruby libraries) is easy! In this example we'll add a HTML validation method that calls the W3C validator service. Please note that if you are planning to batch test a large number of pages, W3C will throttle your access to the validator. In this case you should install a local copy of the validator service first.

First, we add a method to the Raakt module:

# Extends the RAAKT module with a HTML validation mehod.
module Raakt
  class ValidatorError < RuntimeError; end
  class Test
    def validate_markup(url)
      require 'open-uri'
      require 'uri'
      require 'timeout'
      validator_url = "http://validator.w3.org/check?uri="
      escaped_url = URI.escape(url, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
      error_count = -1
        timeout(45) {
          open( validator_url + escaped_url) do |httpcall|
            error_count = httpcall.meta['x-w3c-validator-errors'] if httpcall.meta['x-w3c-validator-errors']
            puts "Validator returned " + error_count 
      rescue Timeout::Error
        raise "Could not validate #{url}. The server did not respond."
        #validator failed (typially due to encoding error)  
        return -1
      return error_count

Save this file as raakt_extensions.rb. Then you can require raakt and raakt_extensions in your ruby script like this:

require 'rubygems'
require 'raakt_extensions'
require 'raakt'
raakttest = Raakt::Test.new
validation_result = raakttest.validate_markup("http://www.google.com")
print "The validator returned #{validation_result}."
examples/extending.txt · Last modified: 2008-09-14 15:01 by peterkz
Recent changes RSS feed, Powered by DokuWiki