Created
August 15, 2011 10:15
-
-
Save julik/1146002 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'uri' | |
module Julik | |
module AbsolutizeHelper | |
def canonicalize_hyperlinks(htmlcontent, root, host = nil, prot = nil) | |
htmlcontent.gsub(/(<(img|a)\b[^>]*(src|href)=)(["'])(.*?)\4/) do | |
md = $~ | |
prefix = (host && prot) ? (prot + host) : '' | |
prefix.gsub!(/\/$/, '') | |
begin | |
url = URI.parse CGI.unescapeHTML(md[5]) | |
prefix = '' if (md[5].include?(prefix) && prefix.length > 0) | |
if url.relative? && url.path !~ /^\// | |
absolutized = File.expand_path(File.join(root, md[5], md[4])) | |
# Clean the trailing slash but leave the quote | |
absolutized.gsub!(/(\/)(["'])$/) { $2 } | |
md[1] + md[4] + prefix + absolutized | |
else | |
md[1] + md[4] + prefix + md[5] + md[4] | |
end | |
rescue URI::InvalidURIError | |
md[0] | |
end | |
end | |
end | |
def canonicalize_hyperlinks_in_context(html) | |
host = request.host | |
proto = request.protocol | |
# honor substandard port | |
host += ":#{request.port}" unless request.port == '80' | |
canonicalize_hyperlinks(html, '/', request.host, request.protocol) | |
end | |
def markdown_with_canonic_links(text) | |
canonicalize_hyperlinks_in_context(markdown(text)) | |
end | |
def textilize_with_canonic_links(text) | |
canonicalize_hyperlinks_in_context(textilize(text)) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment