From 80757346f677cdaeb4f47befa85302b5eba12b7e Mon Sep 17 00:00:00 2001 From: Laurence de Bruxelles Date: Thu, 20 Jan 2022 11:44:24 +0000 Subject: [PATCH] Add extension to middleman-sprockets to get http_prefix in Sass We want to be able to prefix directory paths with the http_prefix in Sass, however normally the `asset-path` helper tries to add a file extension, so this commit adds a small extension that skips the usual logic if the path ends with `/`. The extension works by reaching into the `Sprockets::Envionment` instance in the `middleman-sprockets` extension [1], and replacing the definition of the method `asset_path` [2]. Sprockets turns any calls to `asset-path` in any CSS/Sass it processes into a call to this method, so this is our way to smuggle information into our Sass. [1]: https://github.com/middleman/middleman-sprockets/blob/a32cbe3c8ca129b608bdc852c7ff7ad489f9a087/lib/middleman-sprockets/extension.rb#L28 [2]: https://github.com/middleman/middleman-sprockets/blob/a32cbe3c8ca129b608bdc852c7ff7ad489f9a087/lib/middleman-sprockets/extension.rb#L58 --- lib/govuk_tech_docs.rb | 2 ++ lib/govuk_tech_docs/http_prefix_extension.rb | 21 ++++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 lib/govuk_tech_docs/http_prefix_extension.rb diff --git a/lib/govuk_tech_docs.rb b/lib/govuk_tech_docs.rb index cd19219f..fd454d52 100644 --- a/lib/govuk_tech_docs.rb +++ b/lib/govuk_tech_docs.rb @@ -22,6 +22,7 @@ require "govuk_tech_docs/unique_identifier_generator" require "govuk_tech_docs/warning_text_extension" require "govuk_tech_docs/api_reference/api_reference_extension" +require "govuk_tech_docs/http_prefix_extension" module GovukTechDocs # Configure the tech docs template @@ -65,6 +66,7 @@ def self.configure(context, options = {}) context.activate :unique_identifier context.activate :warning_text context.activate :api_reference + context.activate :sass_http_prefix context.helpers do include GovukTechDocs::TableOfContents::Helpers diff --git a/lib/govuk_tech_docs/http_prefix_extension.rb b/lib/govuk_tech_docs/http_prefix_extension.rb new file mode 100644 index 00000000..82dc427f --- /dev/null +++ b/lib/govuk_tech_docs/http_prefix_extension.rb @@ -0,0 +1,21 @@ +module GovukTechDocs + class SassHttpPrefixExtension < Middleman::Extension + def after_configuration + app.extensions[:sprockets].environment.context_class.class_eval do + # Override the `asset-path()` helper available in Sprockets to + # return a directory rather than a file if the path ends with `/` + alias_method :orig_asset_path, :asset_path + + def asset_path path, options = {} + if options.empty? && path.end_with?("/") + File.join(*[app.config[:http_prefix], path].compact) + else + orig_asset_path path, options + end + end + end + end + end +end + +::Middleman::Extensions.register(:sass_http_prefix, GovukTechDocs::SassHttpPrefixExtension)