Class: CssClassDuplicates::Parser

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

Overview

This class searches for CSS classes

Constant Summary collapse

MATCHER =
/
  \s+class\s*=\s*["']?([\w\s\-_:]+)["']?|       # class = "hello world"
  class:\s*["']?([\w\s\-_:]+)["']?|             # class: 'hello world'
  ["']?class["']?\s=>\s*["']?([\w\s\-_:]+)["']? # 'class' => "hello world"
/x.freeze
WHITESPACE =
/\s/.freeze

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Parser

Returns a new instance of Parser.



13
14
15
16
17
18
# File 'lib/css_class_duplicates/parser.rb', line 13

def initialize(config)
  classes = config.dig('classes')
  @include = to_regex_array(classes&.dig('include'))
  @exclude = to_regex_array(classes&.dig('exclude'))
  @delete = to_regex_array(classes&.dig('delete'))
end

Instance Method Details

#call(file_name) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/css_class_duplicates/parser.rb', line 20

def call(file_name)
  content = File.read(file_name)

  matches = Scanner.new(content).matches(MATCHER)
  matches.map do |match, line|
    classes = match.split(WHITESPACE).reject(&:empty?)
    next if classes.empty?

    classes = filter(classes.map(&:downcase).sort)
    next if classes.empty?

    Match.new(classes, ["#{file_name}:#{line}"])
  end.compact
end