Sha256: 7742acfa1f006d81cc3b5b390c25d4b1079ef13732820f8533df2a4a7eac399e

Contents?: true

Size: 1.14 KB

Versions: 1

Compression:

Stored size: 1.14 KB

Contents

module SprocketsRelativeUrl
  class Processor < Sprockets::Processor
    CSS_URL_REGEXP = /
      (?<=[^a-zA-Z0-9_-]url\()  # Match url\( prefix
      \s*
      (?<q>['"]?)               # Opening quote
      (?<path>[^\)]+?)          # Capture actual path
      \k<q>                     # 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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
sprockets_relative_url-1.0.0 lib/sprockets_relative_url/processor.rb