This post originated from an RSS feed registered with Ruby Buzz
by Red Handed.
Original Post: A MouseHole Example: Showing Alt Text
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
I figured some of you might want to tinker with a simple MouseHole user script, so I translated one of the most basic GreaseMonkey strips: comicalt.user.js by Adam Vandenberg, which reveals the alt text for a comic strip right below the strip.
The MouseHole equivalent (userScripts/comicalt.user.rb) looks like so:
MouseHole.script do
# declaration
name "Comics Alt Text"
namespace "http://adamv.com/greases/"
description 'Shows the "hover text" for some comics on the page'
include_match %r!^http://.*achewood\.com/!
include_match %r!^http://.*qwantz\.com/!
version "0.2"
# instance variables
@comics = {
'achewood' => '//img[starts-with(@src, "/comic.php?date=")]',
'qwantz' => '//img[starts-with(@src, "/comics/")]'
}
# the pages flow through here
def start( req, res )
whichSite = case req.request_uri.host
when /achewood/: "achewood"
when /qwantz/: "qwantz"
end
return unless whichSite
comic = document.elements[@comics[whichSite]]
return unless comic
if comic.attributes['title']
div = Element.new 'div'
div.attributes['className'] = 'msg'
div.text = "(#{ comic.attributes['title'] })"
comic.parent.insert_after comic, div
end
end
end
In all, very similiar to Greasemonkey. The declaration has been moved into the code. The include and exclude directives have been replaced with include_match and exclude_match, which both take regexps.
The start method receives WEBrick’s HTTPRequest and HTTPResponse objects. You can use these to read headers or to add headers.
The HTML itself is parsed by MouseHole and stuck in the user script’s @document instance variable. Modify the document with REXML and the altered document will be delivered back to the browser when you’re done. REXML is mixed into MouseHole, so you can refer to Element and Document without the module name.