FriendFX
FriendFX

Reputation: 3079

Disable did_you_mean gem from within a script

I read that you can disable the did_you_mean gem (which is enabled by default) via the Ruby command line like so:

ruby --disable-did_you_mean script.rb

Is there a way to the same from within script.rb instead of the command line parameter?

Upvotes: 3

Views: 1064

Answers (2)

Drenmi
Drenmi

Reputation: 8777

The gem works by monkey patching NameError, and prepending DidYouMean::Correctable to its ancestors.

NameError.ancestors
#=> [DidYouMean::Correctable, NameError, StandardError, Exception, Object, Kernel, BasicObject]

You can work around this by redefining DidYouMean::Correctable#to_s as Wand Maker suggested, or you can remove the method from the module altogether:

module DidYouMean::Correctable
  remove_method :to_s
end

which has the same outcome.

Upvotes: 3

Wand Maker
Wand Maker

Reputation: 18762

You can undo the module definition of DidYouMean by re-implementing in your script.rb, wherein you delegate the error handler to original Ruby implementation.

# Beginning of script.rb
module DidYouMean
  module Correctable
    prepend_features NameError
    def to_s
      super
    end
  end
end

ary = [1,2]
ary.att(0)

#=> undefined method `att' for [1, 2]:Array
#   (repl):15:in `<main>'

Upvotes: 2

Related Questions