| 1 |
require_relative "../spell_checker" |
| 2 |
|
| 3 |
module DidYouMean |
| 4 |
class MethodNameChecker |
| 5 |
attr_reader :method_name, :receiver |
| 6 |
|
| 7 |
NAMES_TO_EXCLUDE = { NilClass => nil.methods } |
| 8 |
NAMES_TO_EXCLUDE.default = [] |
| 9 |
Ractor.make_shareable(NAMES_TO_EXCLUDE) if defined?(Ractor) |
| 10 |
|
| 11 |
# +MethodNameChecker::RB_RESERVED_WORDS+ is the list of reserved words in |
| 12 |
# Ruby that take an argument. Unlike |
| 13 |
# +VariableNameChecker::RB_RESERVED_WORDS+, these reserved words require |
| 14 |
# an argument, and a +NoMethodError+ is raised due to the presence of the |
| 15 |
# argument. |
| 16 |
# |
| 17 |
# The +MethodNameChecker+ will use this list to suggest a reversed word if |
| 18 |
# a +NoMethodError+ is raised and found closest matches. |
| 19 |
# |
| 20 |
# Also see +VariableNameChecker::RB_RESERVED_WORDS+. |
| 21 |
RB_RESERVED_WORDS = %i( |
| 22 |
alias |
| 23 |
case |
| 24 |
def |
| 25 |
defined? |
| 26 |
elsif |
| 27 |
end |
| 28 |
ensure |
| 29 |
for |
| 30 |
rescue |
| 31 |
super |
| 32 |
undef |
| 33 |
unless |
| 34 |
until |
| 35 |
when |
| 36 |
while |
| 37 |
yield |
| 38 |
) |
| 39 |
|
| 40 |
Ractor.make_shareable(RB_RESERVED_WORDS) if defined?(Ractor) |
| 41 |
|
| 42 |
def initialize(exception) |
| 43 |
@method_name = exception.name |
| 44 |
@receiver = exception.receiver |
| 45 |
@private_call = exception.respond_to?(:private_call?) ? exception.private_call? : false |
| 46 |
end |
| 47 |
|
| 48 |
def corrections |
| 49 |
@corrections ||= begin |
| 50 |
dictionary = method_names |
| 51 |
dictionary = RB_RESERVED_WORDS + dictionary if @private_call |
| 52 |
|
| 53 |
SpellChecker.new(dictionary: dictionary).correct(method_name) - names_to_exclude |
| 54 |
end |
| 55 |
end |
| 56 |
|
| 57 |
def method_names |
| 58 |
if Object === receiver |
| 59 |
method_names = receiver.methods + receiver.singleton_methods |
| 60 |
method_names += receiver.private_methods if @private_call |
| 61 |
method_names.uniq! |
| 62 |
# Assume that people trying to use a writer are not interested in a reader |
| 63 |
# and vice versa |
| 64 |
if method_name.match?(/=\Z/) |
| 65 |
method_names.select! { |name| name.match?(/=\Z/) } |
| 66 |
else |
| 67 |
method_names.reject! { |name| name.match?(/=\Z/) } |
| 68 |
end |
| 69 |
method_names |
| 70 |
else |
| 71 |
[] |
| 72 |
end |
| 73 |
end |
| 74 |
|
| 75 |
def names_to_exclude |
| 76 |
Object === receiver ? NAMES_TO_EXCLUDE[receiver.class] : [] |
| 77 |
end |
| 78 |
end |
| 79 |
end |