require 'cgi'
require 'uri'
class RewriteLinks
=begin
def initialize(html)
@doc = REXML::Document.new("
" + html + "
")
end
def relative_to(url)
@doc.elements.each("//img") { |element|
if element.attributes["src"] !~ %r{\A\w+://}
element.attributes["src"] = url + "/" + element.attributes["src"]
end
}
@doc.elements.each("//a") { |element|
if element.attributes["href"] !~ %r{\A\w+://}
element.attributes["href"] = url + "/" + element.attributes["href"]
end
}
@doc.root[0..-1].to_s # Drop
end
=end
def initialize(html)
@html = html
end
def relative_to(root)
@html.gsub(/(<(img|a)\b[^>]*(src|href)=)(["'])(.*?)\4/) {
md = $~
url = URI.parse CGI.unescapeHTML(md[5])
if url.relative? && url.path !~ /^\//
md[1] + md[4] + root + "/" + md[5] + md[4]
else
md.to_s
end
}
end
end