From cec51e3fa3c7b38c79e7804a2a42286bd2f77d0b Mon Sep 17 00:00:00 2001 From: Petrik Date: Thu, 1 May 2025 12:27:55 +0200 Subject: [PATCH] Add support for canonical URL link Currently, search engines don't know which version to show for API documentation. For example, searching for "ruby string" in Google will show the documentation for Ruby 2.0 `https://docs.ruby-lang.org/en/2.0.0/String.html` as the top result (for docs.ruby-lang.org). The canonical URL link tag will allow us to set the preferred version: > The canonical URL link tag defines the preferred URL for the current > document, which helps search engines reduce duplicate content. https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel#canonical For example, for the official Ruby documentation we can add the following to `.rdoc_options`. ```yaml canonical_root: https://docs.ruby-lang.org/en/master ``` This will add the canonical URL link tag to relevant pages. Co-authored-by: Stan Lo --- lib/rdoc/generator/markup.rb | 12 +++++++ .../generator/template/darkfish/_head.rhtml | 5 +++ lib/rdoc/options.rb | 7 ++++ test/rdoc/rdoc_generator_darkfish_test.rb | 33 +++++++++++++++++++ test/rdoc/rdoc_options_test.rb | 1 + 5 files changed, 58 insertions(+) diff --git a/lib/rdoc/generator/markup.rb b/lib/rdoc/generator/markup.rb index 206b3c53d4..1c39687040 100644 --- a/lib/rdoc/generator/markup.rb +++ b/lib/rdoc/generator/markup.rb @@ -55,6 +55,18 @@ def cvs_url(url, full_path) end end + ## + # The preferred URL for this object. + + def canonical_url + options = @store.options + if path + File.join(options.canonical_root, path.to_s) + else + options.canonical_root + end + end + end class RDoc::CodeObject diff --git a/lib/rdoc/generator/template/darkfish/_head.rhtml b/lib/rdoc/generator/template/darkfish/_head.rhtml index 9e6fb4f94c..7376fc390e 100644 --- a/lib/rdoc/generator/template/darkfish/_head.rhtml +++ b/lib/rdoc/generator/template/darkfish/_head.rhtml @@ -25,6 +25,11 @@ <%- end -%> <%- end -%> +<%- if canonical_url = @options.canonical_root -%> +<% canonical_url = current.canonical_url if defined?(current) %> + +<%- end -%> +