Class: CSSDeadClass

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ CSSDeadClass

Returns a new instance of CSSDeadClass.



21
22
23
24
25
26
# File 'lib/css_dead_class.rb', line 21

def initialize(opts={})
  @options = self.class.config.dup
  opts.each do |k, v|
    @options[k] = v
  end
end

Class Method Details

.configObject



11
12
13
# File 'lib/css_dead_class.rb', line 11

def self.config
  @_config ||= Config.new
end

.option(key, default = nil, description = nil, options = {}) ⇒ Object



14
15
16
# File 'lib/css_dead_class.rb', line 14

def self.option(key, default=nil, description=nil, options={})
  self.config[key] = Config.new(default: default, description: description, options: {})
end

Instance Method Details

#parseObject



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
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/css_dead_class.rb', line 28

def parse
  cssSelectors = []
  cssFiles = @options.css_files
  htmlFiles = @options.html_files
  classesToKeep = @options.classes_to_keep
  if cssFiles.length > 0
    parser = CssParser::Parser.new
    cssFiles.each do |cssFile|
      parser.load_file!(cssFile)
    end 
    parser.each_selector(:screen).each do |rule|
      rule = rule[:rules]
      rule.selectors.each do |segment|
        segment.split(/(?: |\+|>)/).each do |r|
          next if r.include? ":"
          if(r[0] == ".")
            cssSelectors.push(r)
          elsif(r.include? ".")
            s = r.split(".")
            s.shift
            s.each { |v| cssSelectors.push('.' + v)}
          end
        end
      end
    end
    cssSelectors.uniq!
  end
  if cssSelectors.length > 0
    htmlFiles.each do |htmlFile|
      htmlDoc = Nokogiri::HTML(IO.read(htmlFile))
      htmlDoc.css('*').each do |node|
        next if node.attributes.nil? or node.attributes['class'].nil?
        node['class'] = node.attributes['class'].value.split(/ /).select{ |cn| 
          cssSelectors.include?('.' + cn) || classesToKeep.include?(cn) || classesToKeep.include?('.' + cn)
        }.join(" ")
        if(node.attributes['class'].value == "")
          node.attributes['class'].remove
        end
      end
      File.open(htmlFile, "w") do |fp|
        fp.puts htmlDoc.to_s
      end
    end
  end
end