Skip to content

Commit

Permalink
Add extension to middleman-sprockets to get http_prefix in Sass
Browse files Browse the repository at this point in the history
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
  • Loading branch information
lfdebrux committed Jan 25, 2022
1 parent e539c73 commit 8075734
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/govuk_tech_docs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions lib/govuk_tech_docs/http_prefix_extension.rb
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit 8075734

Please sign in to comment.