Module: Minifier

Defined in:
lib/minifier/minifier.rb

Overview

minifies a CSS file

Class Method Summary collapse

Class Method Details

.make_file(minified) ⇒ Object

returns a file containing the minified object



31
32
33
34
# File 'lib/minifier/minifier.rb', line 31

def self.make_file(minified) 
  file = StringIO.new(minified)
  return file
end

.minify(input) ⇒ Object

Reads file from input and returns a string with stripped file potentially specify languages in later versions?



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

def self.minify(input)
  #get file

  file = (input.is_a?(IO)) ? input.read : input.dup.to_s
  #comment removal

  file = file.gsub(/\/*\*[\s\S]*?\*\/*/, '')
  
  #whitespace removal 

  file = file.gsub(/\s+/, ' ')
  
  #add semicolons (but prevent redundant) 

  file = file.gsub(/([^;\}])\}/, '\1;}')
  file = file.gsub(/;+\}/, '}')
  
  #RGB values to hex values (for css) - thanks to StackOverflow

  file = file.gsub(/rgb\s*\(\s*([0-9,\s]+)\s*\)/) do |match|
    '#' << $1.scan(/\d+/).map{|n| n.to_i.to_s(16).rjust(2, '0') }.join
  end
  
  # Replace 0(% ...) with just 0 (first two elements) 

  file = file.gsub(/([\s:])([+-]?0)(?:%|em|ex|px|in|cm|mm)/i, '\1\2') #take out the last part 

  
  file.strip
end

.strip_comments(markers = ['#','//']) ⇒ Object

testing for other languages



37
38
39
40
41
42
43
44
# File 'lib/minifier/minifier.rb', line 37

def self.strip_comments(markers = ['#','//'] )
  re = Regexp.union( markers ) # construct a regular expression which will match any of the markers

  if index = (self =~ re)
    self[0, index].rstrip      # slice the string where the regular expression matches, and return it.

  else
    rstrip
  end
end