Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Memoize absolute_url and relative_url filters #7793

Merged
merged 1 commit into from Aug 22, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
50 changes: 30 additions & 20 deletions lib/jekyll/filters/url_filters.rb
Expand Up @@ -9,17 +9,8 @@ module URLFilters
#
# Returns the absolute URL as a String.
def 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
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
Expand All @@ -29,15 +20,8 @@ def absolute_url(input)
#
# Returns a URL relative to the domain root as a String.
def 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
cache = (@context.registers[:cached_relative_urls] ||= {})
cache[input] ||= compute_relative_url(input)
end

# Strips trailing `/index.html` from URLs to create pretty permalinks
Expand All @@ -53,6 +37,32 @@ def strip_index(input)

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("/")
Expand Down