Class: Torba::CssUrlToErbAssetPath

Inherits:
Object
  • Object
show all
Defined in:
lib/torba/css_url_to_erb_asset_path.rb

Overview

Parses content of CSS file and converts its image assets paths into Sprockets’ logical paths.

Since:

  • 0.1.0

Constant Summary collapse

URL_RE =

Since:

  • 0.1.0

/
  (                # $1
    url\(          # url(
    \s*            # optional space
    ['"]?          # optional quote
    (?!data)       # no data URIs
    (?!http[s]?:\/\/)  # no remote URIs
    (?!\/)         # only relative location
  )
  (                # $2
    [^'"?#]+?      # location
  )
  (                # $3
    ([?#][^'"]+?)? # optional query or fragment
    ['"]?          # optional quote
    \s*            # optional space
    \)             # )
  )
/xm

Class Method Summary collapse

Class Method Details

.call(content, file_path) {|image_file_path| ... } ⇒ String

Returns CSS file content where image “url(…)” paths are replaced by ERB interpolations “url(<%= asset_path(…) %>)”.

Examples:

content = \
  ".react-toolbar {
    width: 100%;
    background: url('./images/toolbar.png');
  }"

new_content = CssUrlToErbAssetPath.call(content, "/var/downloads/react_unzipped/styles.css") do |url|
  url.sub("/var/downloads/react_unzipped/images", "react-toolbar-js"
end

new_content #=>
  ".react-toolbar {
    width: 100%;
    background: url('<%= asset_path('react-toolbar-js/toolbar.png') %>');
  }"

Parameters:

  • content (String)

    content of original CSS file

  • file_path (String)

    absolute path to original CSS file

Yields:

  • (image_file_path)

Yield Parameters:

  • image_file_path (String)

    absolute path to original image file which is mentioned within CSS file

Yield Returns:

  • (String)

    logical path to image file within Sprockets’ virtual filesystem.

Returns:

  • (String)

    CSS file content where image “url(…)” paths are replaced by ERB interpolations “url(<%= asset_path(…) %>)”.

Since:

  • 0.1.0



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/torba/css_url_to_erb_asset_path.rb', line 51

def self.call(content, file_path)
  content.gsub(URL_RE) do
    absolute_image_file_path = File.expand_path($2, File.dirname(file_path))
    sprockets_file_path = yield absolute_image_file_path
    if sprockets_file_path
      "#{$1}<%= asset_path('#{sprockets_file_path}') %>#{$3}"
    else
      $&
    end
  end
end