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

/
  url\(     # url(
  \s*       # optional space
  (?!data)  # no data URIs
  ['"]?     # optional quote
  (?!\/)    # only relative location
  ([^'"]+?) # location
  ['"]?     # 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


43
44
45
46
47
48
49
# File 'lib/torba/css_url_to_erb_asset_path.rb', line 43

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