【问题标题】:How to solve Rubocop respond_to_missing? offence如何解决 Rubocop respond_to_missing?罪行
【发布时间】:2016-12-01 00:48:40
【问题描述】:

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[$1.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 。

【问题讨论】:

  • 将 cmets # rubocop:disable Style/MethodMissing 放在冒犯行之前,# rubocop:enable Style/MethodMissing 紧随其后。 Rubocop 只是个警察,它可能会犯错误。
  • 顺便说一句:如果你只是想传递你收到的相同参数,你可以在没有参数列表的情况下调用super。这与您的问题无关,这似乎是 Rubocop 根本无法看到有一条路径导致super 调用(请记住,几乎任何甚至远程有趣的静态分析都相当于解决停止问题,并且 Ruby 并非完全设计为易于静态分析以启动)。或者,也许,它实际上确实闭嘴了。

标签: ruby rubocop


【解决方案1】:

Rubocop 期望在没有参数的情况下调用 super。由于您传递给super 的参数与您收到的参数相同,您可以简单地删除这些参数:

def method_missing(name, *args, &block)
  if name =~ /(.+)\=/
    self[$1.to_sym] = args[0]
  elsif has_index?(name)
    self[name]
  else
    super
  end
end

【讨论】:

  • 感谢@Justin 参与此活动。我想你可能已经找到了另一个失踪的警察。 :-) 类似于Lint/UselessSuperArguments
【解决方案2】:

也许您应该改用def respond_to_missing?(name, include_private=false)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-05
    • 2012-11-27
    • 2011-07-19
    • 2014-01-10
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多