Skip to content

Commit

Permalink
Process css files so that they get digested paths for asset files
Browse files Browse the repository at this point in the history
This is required so that we can use cssbundling-rails and reference images that will receive digested paths
  • Loading branch information
jcoyne committed Oct 18, 2021
1 parent 118ce60 commit 92b588e
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/sprockets/rails/asset_url_processor.rb
@@ -0,0 +1,16 @@
module Sprockets
module Rails
# Rewrites urls in CSS files with the digested paths
class AssetUrlProcessor
REGEX = /url\(\s*["']?(?!(?:\#|data|http))([^"'\s)]+)\s*["']?\)/

def self.call(input)
context = input[:environment].context_class.new(input)
data = input[:data].gsub(REGEX) do |_match|
"url(#{context.asset_path($1)})"
end
{ data: data }
end
end
end
end
6 changes: 6 additions & 0 deletions lib/sprockets/railtie.rb
Expand Up @@ -4,6 +4,8 @@
require 'active_support/core_ext/module/remove_method'
require 'active_support/core_ext/numeric/bytes'
require 'sprockets'

require 'sprockets/rails/asset_url_processor'
require 'sprockets/rails/context'
require 'sprockets/rails/helper'
require 'sprockets/rails/quiet_assets'
Expand Down Expand Up @@ -116,6 +118,10 @@ def configure(&block)
end
end

initializer :asset_url_processor do |app|
Sprockets.register_postprocessor "text/css", ::Sprockets::Rails::AssetUrlProcessor
end

config.assets.version = ""
config.assets.debug = false
config.assets.compile = true
Expand Down
27 changes: 27 additions & 0 deletions test/test_asset_url_processor.rb
@@ -0,0 +1,27 @@
require 'minitest/autorun'
require 'sprockets/railtie'


Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
class TestAssetUrlProcessor < Minitest::Test
def setup
@env = Sprockets::Environment.new
@env.context_class.class_eval do
def asset_path(path, options = {})
'image-hexcodegoeshere.png'
end
end
end

def test_digest_with_single_quote
input = { environment: @env, data: "url('image.png')", filename: 'url2.css', metadata: {} }
output = Sprockets::Rails::AssetUrlProcessor.call(input)
assert_equal({ data: "url(image-hexcodegoeshere.png)" }, output)
end

def test_digest_with_double_quote
input = { environment: @env, data: 'url("image.png")', filename: 'url2.css', metadata: {} }
output = Sprockets::Rails::AssetUrlProcessor.call(input)
assert_equal({ data: "url(image-hexcodegoeshere.png)" }, output)
end
end

0 comments on commit 92b588e

Please sign in to comment.