summaryrefslogtreecommitdiff
path: root/lib/did_you_mean/core_ext/name_error.rb
blob: 8c170c4b90f9dae73b0b15e846e699eb5e058173 (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
module DidYouMean
  module Correctable
    if Exception.method_defined?(:detailed_message)
      # just for compatibility
      def original_message
        # we cannot use alias here because
        to_s
      end

      def detailed_message(highlight: true, did_you_mean: true, **)
        msg = super.dup

        return msg unless did_you_mean

        suggestion = DidYouMean.formatter.message_for(corrections)

        if highlight
          suggestion = suggestion.gsub(/.+/) { "\e[1m" + $& + "\e[m" }
        end

        msg << suggestion
        msg
      rescue
        super
      end
    else
      SKIP_TO_S_FOR_SUPER_LOOKUP = true
      private_constant :SKIP_TO_S_FOR_SUPER_LOOKUP

      def original_message
        meth = method(:to_s)
        while meth.owner.const_defined?(:SKIP_TO_S_FOR_SUPER_LOOKUP)
          meth = meth.super_method
        end
        meth.call
      end

      def to_s
        msg = super.dup
        suggestion = DidYouMean.formatter.message_for(corrections)

        msg << suggestion if !msg.include?(suggestion)
        msg
      rescue
        super
      end
    end

    def corrections
      @corrections ||= spell_checker.corrections
    end

    def spell_checker
      DidYouMean.spell_checkers[self.class.to_s].new(self)
    end
  end
end