DidYouMean 模块
DidYouMean
gem 添加了在错误(例如 NameError
和 NoMethodError
)中建议可能的方法/类名称的功能。在 Ruby 2.3 或更高版本中,它会在启动期间自动激活。
@example
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 控制台+、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
方法,并返回人类可读的字符串。- SPELL_CHECKERS
TODO:在 3.4 开发开始时删除
- VERSION
- VerboseFormatter
DidYouMean::Formatter
是 gem 的基本默认格式化程序。格式化程序响应message_for
方法,并返回人类可读的字符串。
公共类方法
correct_error(error_class, spell_checker) 单击以切换源
使用给定的拼写检查器向错误添加 DidYouMean
功能
# 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
formatter() 单击以切换源
返回当前设置的格式化程序。默认情况下,它设置为 DidYouMean::Formatter
。
# File lib/did_you_mean.rb, line 141 def self.formatter if defined?(Ractor) Ractor.current[:__did_you_mean_formatter__] || Formatter else Formatter end end
formatter=(formatter) 单击以切换源
更新用于格式化建议的主要格式化程序。
# File lib/did_you_mean.rb, line 150 def self.formatter=(formatter) if defined?(Ractor) Ractor.current[:__did_you_mean_formatter__] = formatter end end
spell_checkers() 单击以切换源
返回错误类型和拼写检查器对象的共享哈希映射。
# File lib/did_you_mean.rb, line 92 def self.spell_checkers @spell_checkers end