summaryrefslogtreecommitdiff
path: root/lib/did_you_mean/spell_checkers/name_error_checkers/variable_name_checker.rb
blob: 3e51b4fa3aeb7e0345804efddddaea8228b825e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
73
74
75
76
77
78
79
80
81
82
# frozen-string-literal: true

require_relative "../../spell_checker"

module DidYouMean
  class VariableNameChecker
    attr_reader :name, :method_names, :lvar_names, :ivar_names, :cvar_names

    NAMES_TO_EXCLUDE = { 'foo' => [:fork, :for] }
    NAMES_TO_EXCLUDE.default = []

    # +VariableNameChecker::RB_RESERVED_WORDS+ is the list of all reserved
    # words in Ruby. They could be declared like methods are, and a typo would
    # cause Ruby to raise a +NameError+ because of the way they are declared.
    #
    # The +:VariableNameChecker+ will use this list to suggest a reversed word
    # if a +NameError+ is raised and found closest matches, excluding:
    #
    #   * +do+
    #   * +if+
    #   * +in+
    #   * +or+
    #
    # Also see +MethodNameChecker::RB_RESERVED_WORDS+.
    RB_RESERVED_WORDS = %i(
      BEGIN
      END
      alias
      and
      begin
      break
      case
      class
      def
      defined?
      else
      elsif
      end
      ensure
      false
      for
      module
      next
      nil
      not
      redo
      rescue
      retry
      return
      self
      super
      then
      true
      undef
      unless
      until
      when
      while
      yield
      __LINE__
      __FILE__
      __ENCODING__
    )

    def initialize(exception)
      @name       = exception.name.to_s.tr("@", "")
      @lvar_names = exception.respond_to?(:local_variables) ? exception.local_variables : []
      receiver    = exception.receiver

      @method_names = receiver.methods + receiver.private_methods
      @ivar_names   = receiver.instance_variables
      @cvar_names   = receiver.class.class_variables
      @cvar_names  += receiver.class_variables if receiver.kind_of?(Module)
    end

    def corrections
      @corrections ||= SpellChecker
                     .new(dictionary: (RB_RESERVED_WORDS + lvar_names + method_names + ivar_names + cvar_names))
                     .correct(name) - NAMES_TO_EXCLUDE[@name]
    end
  end
end