Class: Jekyll::URL

Inherits:
Object
  • Object
show all
Defined in:
lib/jekyll/url.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ URL

options - One of :permalink or :template must be supplied.

:template     - The String used as template for URL generation,
                for example "/:path/:basename:output_ext", where
                a placeholder is prefixed with a colon.
:placeholders - A hash containing the placeholders which will be
                replaced when used inside the template. E.g.
                { "year" => Time.now.strftime("%Y") } would replace
                the placeholder ":year" with the current year.
:permalink    - If supplied, no URL will be generated from the
                template. Instead, the given permalink will be
                used as URL.


24
25
26
27
28
29
30
31
32
# File 'lib/jekyll/url.rb', line 24

def initialize(options)
  @template = options[:template]
  @placeholders = options[:placeholders] || {}
  @permalink = options[:permalink]

  if (@template || @permalink).nil?
    raise ArgumentError, "One of :template or :permalink must be supplied."
  end
end

Instance Method Details

#generate_urlObject

Internal: Generate the URL by replacing all placeholders with their respective values

Returns the unsanitizied String URL



45
46
47
48
49
# File 'lib/jekyll/url.rb', line 45

def generate_url
  @placeholders.inject(@template) do |result, token|
    result.gsub(/:#{token.first}/, token.last)
  end
end

#sanitize_url(in_url) ⇒ Object

Returns a sanitized String URL



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/jekyll/url.rb', line 52

def sanitize_url(in_url)
  # Remove all double slashes
  url = in_url.gsub(/\/\//, "/")

  # Remove every URL segment that consists solely of dots
  url = url.split('/').reject{ |part| part =~ /^\.+$/ }.join('/')

  # Append a trailing slash to the URL if the unsanitized URL had one
  url += "/" if in_url =~ /\/$/

  # Always add a leading slash
  url.gsub!(/\A([^\/])/, '/\1')
  url
end

#to_sObject

The generated relative URL of the resource

Returns the String URL



37
38
39
# File 'lib/jekyll/url.rb', line 37

def to_s
  sanitize_url(@permalink || generate_url)
end