Class: ContentUrls::CssParser

Inherits:
Object
  • Object
show all
Defined in:
lib/content_urls/parsers/css_parser.rb

Overview

CssParser finds and rewrites URLs in CSS content.

Implementation note:

This methods in this class identify URLs by using regular expressions based on the W3C CSS 2.1 Specification (www.w3.org/TR/CSS21/syndata.html).

Class Method Summary collapse

Class Method Details

.rewrite_each_url(content, &block) ⇒ Object

Rewrites each URL in the CSS content by calling the supplied block with each URL.

Examples:

Rewrite URLs in CSS code

css = 'body { background: url(/images/rainbows.jpg) }'
css = ContentUrls::CssParser.rewrite_each_url(css) {|url| url.sub(/rainbows.jpg/, 'unicorns.jpg')}
puts "Rewritten: #{css}"
# => "Rewritten: body { background: url(/images/unicorns.jpg) }"

Parameters:

  • content (String)

    the CSS content.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/content_urls/parsers/css_parser.rb', line 51

def self.rewrite_each_url(content, &block)
  done = false
  remaining = content
  rewritten = ''
  while ! remaining.empty?
    if match = @@regex_uri.match(remaining)
      url = match[7] || match[14] || match[23]
      rewritten += match.pre_match
      remaining = match.post_match
      replacement = yield url
      rewritten += (replacement.nil? ? match[0] : match[0].sub(url, replacement))
    else
      rewritten += remaining
      remaining = ''
    end
  end
  return rewritten
end

.urls(content) ⇒ Array

Returns the URLs found in the CSS content.

Examples:

Parse CSS code for URLs

css = 'body { background: url(/images/rainbows.jpg) }'
ContentUrls::CssParser.urls(css).each do |url|
  puts "Found URL: #{url}"
end
# => "Found URL: /images/rainbows.jpg"

Parameters:

  • content (String)

    the CSS content.

Returns:

  • (Array)

    the unique URLs found in the content.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/content_urls/parsers/css_parser.rb', line 20

def self.urls(content)
  urls = []
  remaining = content
  while ! remaining.empty?
    if @@regex_uri =~ remaining
      match = $1
      url = $7 || $14 || $23
      #if @@regex_baduri =~ match  ## bad URL
      #  remaining = remaining[Regexp.last_match.begin(0)+1..-1]  # Use last_match from regex_uri test
      #else
        remaining = Regexp.last_match.post_match
        urls << url
      #end
    else
      remaining = ''
    end
  end
  urls.uniq!
  urls        
end