diff --git a/lib/sprockets/rails/asset_url_processor.rb b/lib/sprockets/rails/asset_url_processor.rb new file mode 100644 index 00000000..c55f4166 --- /dev/null +++ b/lib/sprockets/rails/asset_url_processor.rb @@ -0,0 +1,15 @@ +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) { |_match| "url(#{context.asset_path($1)})" } + + { data: data } + end + end + end +end diff --git a/lib/sprockets/railtie.rb b/lib/sprockets/railtie.rb index da5275ad..d7434523 100644 --- a/lib/sprockets/railtie.rb +++ b/lib/sprockets/railtie.rb @@ -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' @@ -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 diff --git a/test/test_asset_url_processor.rb b/test/test_asset_url_processor.rb new file mode 100644 index 00000000..75ae5610 --- /dev/null +++ b/test/test_asset_url_processor.rb @@ -0,0 +1,39 @@ +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_basic + input = { environment: @env, data: 'background: url(image.png);', filename: 'url2.css', metadata: {} } + output = Sprockets::Rails::AssetUrlProcessor.call(input) + assert_equal({ data: "background: url(image-hexcodegoeshere.png);" }, output) + end + + def test_spaces + input = { environment: @env, data: 'background: url( image.png );', filename: 'url2.css', metadata: {} } + output = Sprockets::Rails::AssetUrlProcessor.call(input) + assert_equal({ data: "background: url(image-hexcodegoeshere.png);" }, output) + end + + def test_single_quote + input = { environment: @env, data: "background: url('image.png');", filename: 'url2.css', metadata: {} } + output = Sprockets::Rails::AssetUrlProcessor.call(input) + assert_equal({ data: "background: url(image-hexcodegoeshere.png);" }, output) + end + + def test_double_quote + input = { environment: @env, data: 'background: url("image.png");', filename: 'url2.css', metadata: {} } + output = Sprockets::Rails::AssetUrlProcessor.call(input) + assert_equal({ data: "background: url(image-hexcodegoeshere.png);" }, output) + end +end