Class: Distil::CssDependencyTask

Inherits:
Task show all
Defined in:
lib/distil/task/css-dependency-task.rb

Instance Attribute Summary

Attributes inherited from Configurable

#options

Instance Method Summary collapse

Methods inherited from Task

#find_files, #handles_file?, inherited, #initialize, #process_files, #project, #target, tasks

Methods inherited from Configurable

#get_option, #get_options, #initialize, option

Constructor Details

This class inherits a constructor from Distil::Task

Instance Method Details

#handles_file(file) ⇒ Object



7
8
9
# File 'lib/distil/task/css-dependency-task.rb', line 7

def handles_file(file)
  return ["css"].include?(file.content_type)
end

#include_file(file) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/distil/task/css-dependency-task.rb', line 11

def include_file(file)
  return if !handles_file(file)

  content= target.get_content_for_file(file)

  # Replace all ' (single quotes) with " (double quotes)
  content.gsub!(/\'/,'"')
  # Force a newline after a rule terminating ; (semi-colon)
  content.gsub!(/;(\n|\r)*/, ";\n")

  source_folder= get_option("source_folder")
  
  # Rewrites the 'url("...")' rules to a relative path 
  # based on the location of the new concatenated CSS file.
  line_num=0

  lines= content.split("\n")

  lines.each { |line|

    line_num+=1

    line.gsub!(CSS_IMPORT_REGEX) { |match|
      css_file= File.join(file.parent_folder, $1)

      if (!File.exists?(css_file))
        file.error "Imported CSS file not found: #{$1}", line_num
        # leave the @import rule in place
        match
      else
        file.add_dependency(SourceFile.from_path(css_file))
      end
    }
  
    line.gsub!(/url\("?(.*\.(jpg|png|gif))"?\)/) { |match|
      image_file= File.join(file.parent_folder, $1)

      if (!File.exists?(image_file))
        file.warning "Resource not found: #{$1} (#{image_file})", line_num
        "url(\"#{$1}\")"
      else
        asset= SourceFile.from_path(image_file)
        file.add_asset(asset)
        "url(\"#{asset.relative_to_folder(source_folder)}\")"
      end
    }
  }

  target.set_content_for_file(file, lines.join("\n"))
end