module SprocketsRelativeUrl class Processor < Sprockets::Processor CSS_URL_REGEXP = / (?<=[^a-zA-Z0-9_-]url\() # Match url\( prefix \s* (?['"]?) # Opening quote (?[^\)]+?) # Capture actual path \k # Backref for closing quote \s* (?=\)) # Match \) terminator /x private_constant :CSS_URL_REGEXP def evaluate(context, *) data.gsub(CSS_URL_REGEXP) do path = Regexp.last_match[:path] next path if should_skip?(path) uri = URI.parse(path) next path if uri.absolute? uri.path = root_relative_path(context, uri.path) uri.to_s end end private def root_relative_path(context, path) decoded = URI.decode(path) asset_full_path = context.pathname.parent.join(decoded) asset = context.environment.find_asset(asset_full_path) return path if asset.nil? encoded = URI.encode(asset.logical_path) context.asset_path(encoded) end def should_skip?(path) path.start_with?('/') || path.include?('\\') end end end