forked from jekyll/jekyll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
url_filters.rb
78 lines (63 loc) · 2.25 KB
/
url_filters.rb
1
2
3
4
5
6
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# frozen_string_literal: true
module Jekyll
module Filters
module URLFilters
# Produces an absolute URL based on site.url and site.baseurl.
#
# input - the URL to make absolute.
#
# Returns the absolute URL as a String.
def absolute_url(input)
cache = (@context.registers[:cached_absolute_urls] ||= {})
cache[input] ||= compute_absolute_url(input)
end
# Produces a URL relative to the domain root based on site.baseurl
# unless it is already an absolute url with an authority (host).
#
# input - the URL to make relative to the domain root
#
# Returns a URL relative to the domain root as a String.
def relative_url(input)
cache = (@context.registers[:cached_relative_urls] ||= {})
cache[input] ||= compute_relative_url(input)
end
# Strips trailing `/index.html` from URLs to create pretty permalinks
#
# input - the URL with a possible `/index.html`
#
# Returns a URL with the trailing `/index.html` removed
def strip_index(input)
return if input.nil? || input.to_s.empty?
input.sub(%r!/index\.html?$!, "/")
end
private
def compute_absolute_url(input)
return if input.nil?
input = input.url if input.respond_to?(:url)
return input if Addressable::URI.parse(input.to_s).absolute?
site = @context.registers[:site]
return relative_url(input) if site.config["url"].nil?
Addressable::URI.parse(
site.config["url"].to_s + relative_url(input)
).normalize.to_s
end
def compute_relative_url(input)
return if input.nil?
input = input.url if input.respond_to?(:url)
return input if Addressable::URI.parse(input.to_s).absolute?
parts = [sanitized_baseurl, input]
Addressable::URI.parse(
parts.compact.map { |part| ensure_leading_slash(part.to_s) }.join
).normalize.to_s
end
def sanitized_baseurl
site = @context.registers[:site]
site.config["baseurl"].to_s.chomp("/")
end
def ensure_leading_slash(input)
return input if input.nil? || input.empty? || input.start_with?("/")
"/#{input}"
end
end
end
end