Class: FontawesomeSubsetter::FontawesomeSassImporter

Inherits:
Object
  • Object
show all
Defined in:
lib/fontawesome_subsetter/subsetter.rb

Overview

Custom Sass importer that intercepts FontAwesome SCSS file loads. Strips the populated $icons and $brand-icons maps from variables.scss in memory, replacing them with empty !default maps so the subsetter can inject only used icons. This avoids requiring users to manually edit their vendor FontAwesome files.

Instance Method Summary collapse

Constructor Details

#initialize(scss_dir) ⇒ FontawesomeSassImporter

Returns a new instance of FontawesomeSassImporter.



16
17
18
# File 'lib/fontawesome_subsetter/subsetter.rb', line 16

def initialize(scss_dir)
  @scss_dir = File.expand_path(scss_dir.to_s)
end

Instance Method Details

#canonicalize(url, context) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/fontawesome_subsetter/subsetter.rb', line 20

def canonicalize(url, context)
  if url.start_with?("file://")
    path = URI.parse(url).path
  elsif context.containing_url
    base = File.dirname(URI.parse(context.containing_url.to_s).path)
    path = File.expand_path(url, base)
  else
    return nil
  end

  candidates = [path, "#{path}.scss", File.join(File.dirname(path), "_#{File.basename(path)}.scss")]
  match = candidates.find { |c| File.exist?(c) && c.start_with?(@scss_dir) }
  return nil unless match

  "file://#{match}"
end

#load(url) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/fontawesome_subsetter/subsetter.rb', line 37

def load(url)
  path = URI.parse(url).path
  content = File.read(path)

  if File.basename(path, ".scss").delete_prefix("_") == "variables"
    content = content.sub(/^\$icons\s*:\s*\(.*?^\)\s*;/m, "$icons: () !default;")
    content = content.sub(/^\$brand-icons\s*:\s*\(.*?^\)\s*;/m, "$brand-icons: () !default;")
  end

  { contents: content, syntax: :scss }
end