Module: Jekyll::UniqueURL::URLSetter

Defined in:
lib/jekyll/unique_urls/url_setter.rb

Overview

Modifies the #url method to check if the URL is a duplicate

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/jekyll/unique_urls/url_setter.rb', line 7

def self.included(base)
  base.class_eval do
    alias original_url url

    # Only do this once.  The first time we check if the URL
    # already exists and add a unique string to it.
    def url
      return @url if @url

      original_url

      if @site.urls.include? @url
        @url = unique_url

        Jekyll.logger.warn "URL for #{relative_path} is duplicate, changing to #{@url}"
      end

      @site.urls << @url

      @url
    end

    # Make the URL unique by appending a unique string to it.  If
    # it's a directory, add it to the directory; if it's a file,
    # add it to the file name.
    def unique_url
      if @url.end_with? '/'
        @url.sub(%r{/\z}, '-' + digest + '/')
      elsif respond_to? :output_ext
        @url.sub(%r{#{output_ext}\z}, '-' + digest + output_ext)
      else
        @url.sub(%r{#{extname}\z}, digest + extname)
      end
    end

    # Paths are unique for every resource type so we just digest
    # those and take the first 8 chars.
    #
    # XXX: What's the chance of collisions?
    def digest
      @digest ||= Digest::SHA256.hexdigest(relative_path)[0..7]
    end
  end
end