Class: Nanoc3::Filters::RelativizePaths

Inherits:
Nanoc3::Filter show all
Includes:
Helpers::LinkTo
Defined in:
lib/nanoc3/filters/relativize_paths.rb

Constant Summary

Constants inherited from Nanoc3::Filter

Nanoc3::Filter::TMP_BINARY_ITEMS_DIR

Instance Attribute Summary

Attributes inherited from Nanoc3::Filter

#assigns

Instance Method Summary collapse

Methods included from Helpers::LinkTo

#link_to, #link_to_unless_current, #relative_path_to

Methods included from Helpers::HTMLEscape

#html_escape

Methods included from Helpers::Capturing

#capture, #content_for

Methods inherited from Nanoc3::Filter

#depend_on, #filename, from_binary?, #initialize, #output_filename, to_binary?, type

Methods included from PluginRegistry::PluginMethods

#identifier, #identifiers, #named, #register

Methods inherited from Context

#get_binding, #initialize

Constructor Details

This class inherits a constructor from Nanoc3::Filter

Instance Method Details

#run(content, params = {}) ⇒ String

Relativizes all paths in the given content, which can be either HTML or CSS. This filter is quite useful if a site needs to be hosted in a subdirectory instead of a subdomain. In HTML, all ‘href` and `src` attributes will be relativized. In CSS, all `url()` references will be relativized.

Parameters:

  • content (String)

    The content to filter

  • params (Hash) (defaults to: {})

    a customizable set of options

Options Hash (params):

  • :type (Symbol)

    The type of content to filter; can be either ‘:html` or `:css`.

Returns:

  • (String)

    The filtered content



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/nanoc3/filters/relativize_paths.rb', line 21

def run(content, params={})
  # Set assigns so helper function can be used
  @item_rep = assigns[:item_rep] if @item_rep.nil?

  # Filter
  # FIXME use nokogiri or csspool instead of regular expressions
  case params[:type]
  when :html
    content.gsub(/(<[^>]+\s+(src|href))=(['"]?)(\/.*?)\3([ >])/) do
      $1 + '=' + $3 + relative_path_to($4) + $3 + $5
    end
  when :css
    content.gsub(/url\((['"]?)(\/.*?)\1\)/) do
      'url(' + $1 + relative_path_to($2) + $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