Class: Packr::Minifier

Inherits:
Object
  • Object
show all
Defined in:
lib/packr/minifier.rb

Constant Summary collapse

CONTINUE =
/\\\r?\n/
CLEAN =
Parser.new.
put("\\(\\s*([^;)]*)\\s*;\\s*([^;)]*)\\s*;\\s*([^;)]*)\\)", "(\\1;\\2;\\3)"). # for (;;) loops
put("throw[^};]+[};]", IGNORE). # a safari 1.3 bug
put(";+\\s*([};])", "\\1")
COMMENTS =
Parser.new.
put(";;;[^\\n]*\\n", REMOVE).
put("(COMMENT1)\\n\\s*(REGEXP)?", "\n\\3").
put("(COMMENT2)\\s*(REGEXP)?", lambda do |*args|
  match, comment, b, regexp = args[0..3]
  if comment =~ /^\/\*@/ and comment =~ /@\*\/$/
  #  comments = Minifier.conditional_comments.exec(comment)
  else
    comment = ""
  end
  comment + " " + (regexp || "")
end)
WHITESPACE =
Parser.new.
put("/\\/\\/@[^\\n]*\\n", IGNORE).
put("@\\s+\\b", "@ "). # protect conditional comments
put("\\b\\s+@", " @").
put("(\\d)\\s+(\\.\\s*[a-z\\$_\\[(])", "\\1 \\2"). # http://dean.edwards.name/weblog/2007/04/packer3/#comment84066
put("([+-])\\s+([+-])", "\\1 \\2"). # c = a++ +b;
put("\\b\\s+\\$\\s+\\b", " $ "). # var $ in
put("\\$\\s+\\b", "$ "). # object$ in
put("\\b\\s+\\$", " $"). # return $object
    # put("\\b\\s+#", " #").   # CSS
put("\\b\\s+\\b", SPACE).
put("\\s+", REMOVE)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMinifier

Returns a new instance of Minifier.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/packr/minifier.rb', line 8

def initialize
  @concat = Packr::CONCAT.union(DATA)

  def @concat.exec(script)
    parsed = super(script)
    while parsed != script
      script = parsed
      parsed = super(script)
    end
    parsed
  end

  @comments = DATA.union(COMMENTS)
  @clean = DATA.union(CLEAN)
  @whitespace = DATA.union(WHITESPACE)

  @@conditional_comments = @comments.copy
  @@conditional_comments.put_at(-1, " \\3")
  @whitespace.remove_at(2) # conditional comments
  @comments.remove_at(2)
end

Class Method Details

.conditional_commentsObject



4
5
6
# File 'lib/packr/minifier.rb', line 4

def self.conditional_comments
  @@conditional_comments
end

.exec(script) ⇒ Object



11
12
13
14
15
16
17
18
# File 'lib/packr/minifier.rb', line 11

def @concat.exec(script)
  parsed = super(script)
  while parsed != script
    script = parsed
    parsed = super(script)
  end
  parsed
end

Instance Method Details

#minify(script) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/packr/minifier.rb', line 30

def minify(script)
  # packing with no additional options
  script += "\n"
  script = script.gsub(CONTINUE, "")
  script = @comments.exec(script)
  script = @clean.exec(script)
  script = @whitespace.exec(script)
  script = @concat.exec(script)
  script
end