Module: CdnHelpers::CssRewriter

Defined in:
lib/cdn_helpers.rb

Class Method Summary collapse

Class Method Details

.process_css_file(logger, css_file, css_file_path, public_root_path, url_prefix = '/') ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/cdn_helpers.rb', line 99

def self.process_css_file(logger, css_file, css_file_path, public_root_path, url_prefix = '/')
  out_lines = []
  css_file_path = Pathname.new(css_file_path).realpath
  public_root_path = Pathname.new(public_root_path)
  context_path = css_file_path.parent
  while line = css_file.gets
    out_lines << line.gsub(/url\(["']?([^"'\)]+)["']?\)/) do |url_match|
      if URI.parse($1).scheme.nil?
        local_url = Pathname.new($1)
        if local_url.relative?
          file_path = context_path.join(local_url).cleanpath.relative_path_from(public_root_path).to_s
        else
          url_prefix = url_prefix + '/' unless url_prefix.rindex('/') == (url_prefix.length - 1)

          if local_url.to_s.index(url_prefix) == 0
            local_url = local_url.to_s[(url_prefix.length - 1)..-1] 
          else
            local_url = local_url.to_s
          end
          
          file_path = public_root_path.join(local_url[1..-1]).cleanpath.relative_path_from(public_root_path).to_s
        end
        "url(#{url_prefix[0..-2]}#{CdnHelpers::AssetPath.hash_file("/" + file_path, public_root_path, logger)})"
      else
        "url(#{$1})"
      end
    end
  end
  css_file.close
  out_lines.join("")
end

.rewrite_css_file(logger, css_file_path, public_root_path, url_prefix = '/') ⇒ Object



92
93
94
95
96
97
# File 'lib/cdn_helpers.rb', line 92

def self.rewrite_css_file(logger, css_file_path, public_root_path, url_prefix = '/')
  logger.info("Rewriting CSS file URLs in #{css_file_path}")
  css_file = File.open(css_file_path)
  output = process_css_file(logger, css_file, css_file_path, public_root_path, url_prefix)
  File.open(css_file_path, 'w') { |f| f.write(output) }
end