Skip to content

Instantly share code, notes, and snippets.

@fracai
Created January 12, 2012 00:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fracai/1597618 to your computer and use it in GitHub Desktop.
Save fracai/1597618 to your computer and use it in GitHub Desktop.
nanoc filter to convert relative paths to absolute
# encoding: utf-8
module Nanoc3::Filters
class AbsolutizePaths < Nanoc3::Filter
identifier :absolutize_paths
require 'nanoc3/helpers/link_to'
include Nanoc3::Helpers::LinkTo
def unstack(current, target)
if target =~ /^\//
return target
end
p = current.gsub(/[^\/]*$/,'') + target
p = p.gsub(/\/+/,'/')
p = p.gsub(/[^\/]*\/\.\.\//,'') while (p =~ /\.\.\//)
p
end
def absolute_path_to(target, params={})
abs_path = target.is_a?(String) ? target : target.path
abs_path = unstack(@item_rep.item.path, abs_path)
if params[:style] == :absolute
abs_path = @site.config[:base_url] + abs_path
end
abs_path
end
def run(content, params={})
# Check attributes
if params[:style] == :absolute and @site.config[:base_url].nil?
raise RuntimeError.new('Cannot build absolute path: site configuration has no base_url')
end
# Set assigns so helper function can be used
@item_rep = assigns[:item_rep] if @item_rep.nil?
# Filter
case params[:type]
when :html
content.gsub(/(<[^>]+\s+(src|href))=(['"]?)([^:]*?)\3([ >])/) do
$1 + '=' + $3 + absolute_path_to($4, params) + $3 + $5
end
when :css
content.gsub(/url\((['"]?)([^:]*?)\1\)/) do
'url(' + $1 + absolute_path_to($2, params) + $1 + ')'
end
else
raise RuntimeError.new(
"The relativize_paths needs to know the type of content to " +
"process. Pass :type => :html for HTML or :type => :css for CSS."
)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment