Memoize absolute_url and relative_url filters (#7793)

Merge pull request 7793
This commit is contained in:
Nikhil Benesch 2019-08-22 09:51:33 -04:00 committed by jekyllbot
parent b9963f38b3
commit 55fba8ff31
1 changed files with 30 additions and 20 deletions

View File

@ -9,17 +9,8 @@ module Jekyll
# #
# Returns the absolute URL as a String. # Returns the absolute URL as a String.
def absolute_url(input) def absolute_url(input)
return if input.nil? cache = (@context.registers[:cached_absolute_urls] ||= {})
cache[input] ||= compute_absolute_url(input)
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 end
# Produces a URL relative to the domain root based on site.baseurl # Produces a URL relative to the domain root based on site.baseurl
@ -29,15 +20,8 @@ module Jekyll
# #
# Returns a URL relative to the domain root as a String. # Returns a URL relative to the domain root as a String.
def relative_url(input) def relative_url(input)
return if input.nil? cache = (@context.registers[:cached_relative_urls] ||= {})
cache[input] ||= compute_relative_url(input)
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 end
# Strips trailing `/index.html` from URLs to create pretty permalinks # Strips trailing `/index.html` from URLs to create pretty permalinks
@ -53,6 +37,32 @@ module Jekyll
private 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 def sanitized_baseurl
site = @context.registers[:site] site = @context.registers[:site]
site.config["baseurl"].to_s.chomp("/") site.config["baseurl"].to_s.chomp("/")