模块 DidYouMean
DidYouMean
gem 为诸如 NameError
和 NoMethodError
等错误添加了建议可能的类/方法名称的功能。在 Ruby 2.3 或更高版本中,它会在启动时自动激活。
@示例
methosd # => NameError: undefined local variable or method `methosd' for main:Object # Did you mean? methods # method OBject # => NameError: uninitialized constant OBject # Did you mean? Object @full_name = "Yuki Nishijima" first_name, last_name = full_name.split(" ") # => NameError: undefined local variable or method `full_name' for main:Object # Did you mean? @full_name @@full_name = "Yuki Nishijima" @@full_anme # => NameError: uninitialized class variable @@full_anme in Object # Did you mean? @@full_name full_name = "Yuki Nishijima" full_name.starts_with?("Y") # => NoMethodError: undefined method `starts_with?' for "Yuki Nishijima":String # Did you mean? start_with? hash = {foo: 1, bar: 2, baz: 3} hash.fetch(:fooo) # => KeyError: key not found: :fooo # Did you mean? :foo
禁用 did_you_mean
¶ ↑
有时,您可能想要禁用 did_you_mean
gem,例如为了调试错误对象本身的问题。您可以通过在 ruby
命令中指定 --disable-did_you_mean
选项来完全禁用它。
$ ruby --disable-did_you_mean -e "1.zeor?" -e:1:in `<main>': undefined method `zeor?' for 1:Integer (NameError)
当您无法直接访问 ruby
命令时(例如 +rails console+, irb
),您可以使用 RUBYOPT
环境变量来应用选项
$ RUBYOPT='--disable-did_you_mean' irb irb:0> 1.zeor? # => NoMethodError (undefined method `zeor?' for 1:Integer)
获取原始错误消息¶ ↑
有时,您不想完全禁用该 gem,但需要获取没有建议的原始错误消息(例如,测试)。在这种情况下,您可以使用错误对象上的 original_message 方法
no_method_error = begin 1.zeor? rescue NoMethodError => error error end no_method_error.message # => NoMethodError (undefined method `zeor?' for 1:Integer) # Did you mean? zero? no_method_error.original_message # => NoMethodError (undefined method `zeor?' for 1:Integer)
常量
- PlainFormatter
-
DidYouMean::Formatter
是该 gem 的基本默认格式化程序。格式化程序响应message_for
方法,并返回人类可读的字符串。 - VERSION
- VerboseFormatter
-
DidYouMean::Formatter
是该 gem 的基本默认格式化程序。格式化程序响应message_for
方法,并返回人类可读的字符串。
公共类方法
源代码
# File lib/did_you_mean.rb, line 97 def self.correct_error(error_class, spell_checker) if defined?(Ractor) new_mapping = { **@spell_checkers, error_class.to_s => spell_checker } new_mapping.default = NullChecker @spell_checkers = Ractor.make_shareable(new_mapping) else spell_checkers[error_class.to_s] = spell_checker end error_class.prepend(Correctable) if error_class.is_a?(Class) && !(error_class < Correctable) end
使用给定的拼写检查器向错误添加 DidYouMean
功能
源代码
# File lib/did_you_mean.rb, line 117 def self.formatter if defined?(Ractor) Ractor.current[:__did_you_mean_formatter__] || Formatter else Formatter end end
返回当前设置的格式化程序。默认情况下,它被设置为 DidYouMean::Formatter
。
源代码
# File lib/did_you_mean.rb, line 126 def self.formatter=(formatter) if defined?(Ractor) Ractor.current[:__did_you_mean_formatter__] = formatter end end
更新用于格式化建议的主要格式化程序。
源代码
# File lib/did_you_mean.rb, line 92 def self.spell_checkers @spell_checkers end
返回错误类型和拼写检查器对象的可共享哈希映射。