Class: SpellingAnalyzer

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

Constant Summary collapse

NAME =
'Spellcheck'.freeze
RULE =
'Common misspelling'.freeze
SEVERITY =
'warning'.freeze
EXTENSIONS =
['.md', '.markdown', '.textile', '.rdoc'].freeze

Instance Method Summary collapse

Constructor Details

#initializeSpellingAnalyzer

Returns a new instance of SpellingAnalyzer.



7
8
9
10
# File 'lib/linty/spelling_analyzer.rb', line 7

def initialize
  path = File.dirname(__FILE__) + '/data/common_misspellings.txt'
  @common_misspellings = File.read(path).lines.map(&:downcase).map!(&:strip)
end

Instance Method Details

#analyze(path) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/linty/spelling_analyzer.rb', line 12

def analyze(path)
  find_text_files(path).each do |file|
    analyze_file(file, path) do |offense|
      yield offense
    end
  end
end

#analyze_file(file, path) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/linty/spelling_analyzer.rb', line 20

def analyze_file(file, path)
  normalized_file = File.expand_path(file).sub(path, '')
  File.read(file).lines.each_with_index do |line, line_num|
    words = find_words(line)
    misspellings = words & @common_misspellings
    misspellings.each do |misspelling|
      yield new_offense(normalized_file, misspelling, line_num)
    end
  end
end

#find_text_files(path) ⇒ Object



42
43
44
45
# File 'lib/linty/spelling_analyzer.rb', line 42

def find_text_files(path)
  files = Dir.glob(path + '/**/*.*')
  files.select { |file| EXTENSIONS.include? File.extname(file) }
end

#find_words(content) ⇒ Object



47
48
49
50
51
# File 'lib/linty/spelling_analyzer.rb', line 47

def find_words(content)
  words = content.downcase.split(/\W+/).uniq
  words.reject!(&:empty?)
  return words
end

#new_offense(file, misspelling, line_num) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/linty/spelling_analyzer.rb', line 31

def new_offense(file, misspelling, line_num)
  Offense.new(
    analyzer: NAME,
    file: file,
    line: line_num,
    rule: RULE,
    severity: SEVERITY,
    message: misspelling
  )
end