Sha256: 442fb901bb273dfc327747b21a6236807ec4ac5b692ebfa5662247a3cc59d4d3

Contents?: true

Size: 1.07 KB

Versions: 6

Compression:

Stored size: 1.07 KB

Contents

# frozen_string_literal: true
require "propshaft/errors"

class Propshaft::Compilers::CssAssetUrls
  attr_reader :assembly

  ASSET_URL_PATTERN = /url\(\s*["']?(?!(?:\#|data|http))([^"'\s)]+)\s*["']?\)/

  def initialize(assembly)
    @assembly = assembly
  end

  def compile(logical_path, input)
    input.gsub(ASSET_URL_PATTERN) { asset_url resolve_path(logical_path.dirname, $1), logical_path, $1 }
  end

  private
    def resolve_path(directory, filename)
      if filename.start_with?("../")
        Pathname.new(directory + filename).relative_path_from("").to_s
      elsif filename.start_with?("/")
        filename.delete_prefix("/").to_s
      else
        (directory + filename.delete_prefix("./")).to_s
      end
    end

    def asset_url(resolved_path, logical_path, pattern)
      if asset = assembly.load_path.find(resolved_path)
        %[url("#{assembly.config.prefix}/#{asset.digested_path}")]
      else
        Propshaft.logger.warn "Unable to resolve '#{pattern}' for missing asset '#{resolved_path}' in #{logical_path}"
        %[url("#{pattern}")]
      end
    end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
propshaft-0.5.0 lib/propshaft/compilers/css_asset_urls.rb
propshaft-0.4.4 lib/propshaft/compilers/css_asset_urls.rb
propshaft-0.4.3 lib/propshaft/compilers/css_asset_urls.rb
propshaft-0.4.2 lib/propshaft/compilers/css_asset_urls.rb
propshaft-0.4.1 lib/propshaft/compilers/css_asset_urls.rb
propshaft-0.4.0 lib/propshaft/compilers/css_asset_urls.rb