如何解决 Rubocop respond_to_missing?罪行
How to solve Rubocop respond_to_missing? offence
Rubocop 给我以下罪行
lib/daru/vector.rb:1182:5: C: Style/MethodMissing: When using method_missing, define respond_to_missing? and fall back on super.
def method_missing(name, *args, &block) ...
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
缺少的方法定义为:
def method_missing(name, *args, &block)
if name =~ /(.+)\=/
self[.to_sym] = args[0]
elsif has_index?(name)
self[name]
else
super(name, *args, &block)
end
end
我试着用下面的代码修复它,看到了 here
中的一个例子
def respond_to_missing?(method_name, include_private=false)
(name =~ /(.+)\=/) || has_index?(name) || super
end
但现在 Rubocop 给我以下罪行:
lib/daru/vector.rb:1182:5: C: Style/MethodMissing: When using method_missing, fall back on super.
def method_missing(name, *args, &block) ...
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
我似乎无法弄清楚出了什么问题。如您所见,我在 else 块中使用 super。
Rubocop 期望 super
在没有参数的情况下被调用。由于您传递给 super
的参数与您收到的参数相同,您可以简单地删除参数:
def method_missing(name, *args, &block)
if name =~ /(.+)\=/
self[.to_sym] = args[0]
elsif has_index?(name)
self[name]
else
super
end
end
也许你应该试试 def respond_to_missing?(name, include_private=false)
?
Rubocop 给我以下罪行
lib/daru/vector.rb:1182:5: C: Style/MethodMissing: When using method_missing, define respond_to_missing? and fall back on super.
def method_missing(name, *args, &block) ...
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
缺少的方法定义为:
def method_missing(name, *args, &block)
if name =~ /(.+)\=/
self[.to_sym] = args[0]
elsif has_index?(name)
self[name]
else
super(name, *args, &block)
end
end
我试着用下面的代码修复它,看到了 here
中的一个例子def respond_to_missing?(method_name, include_private=false)
(name =~ /(.+)\=/) || has_index?(name) || super
end
但现在 Rubocop 给我以下罪行:
lib/daru/vector.rb:1182:5: C: Style/MethodMissing: When using method_missing, fall back on super.
def method_missing(name, *args, &block) ...
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
我似乎无法弄清楚出了什么问题。如您所见,我在 else 块中使用 super。
Rubocop 期望 super
在没有参数的情况下被调用。由于您传递给 super
的参数与您收到的参数相同,您可以简单地删除参数:
def method_missing(name, *args, &block)
if name =~ /(.+)\=/
self[.to_sym] = args[0]
elsif has_index?(name)
self[name]
else
super
end
end
也许你应该试试 def respond_to_missing?(name, include_private=false)
?