如何让Rubocop检查特定的方法/关键字使用?

3

我希望阻止在我们的代码库中使用 unscoped。在 rubocop 中是否存在允许我指定关键字的现有 linter?如果没有,我是否需要编写自定义 cop 来实现它?


1
unscoped is a method - not a keyword. Keywords are identifiers that have a specific significance to the parser such as if, else, case, do, when - max
看到了这个问题后,我猜想答案是编写一个自定义的 Cop。 - Matouš Borák
1个回答

3

我的同行帮了我。看来我们需要编写自定义剪贴板。

module RuboCop
  module Cop
    module Hired
      class Unscoped < Cop
        MSG = "Avoid using `unscoped`."

        def_node_matcher :unscoped?, <<-END
          (send _ :unscoped)
        END

        def on_send(node)
          return unless unscoped?(node)
          add_offense(node, :expression, MSG % node.source)
        end
      end
    end
  end
end

将其放入文件夹中,比如说 lib/cops/,然后将其添加到.rubocop.yml中:

require:
- ./lib/cops/<whatever_you_called_the_file>.rb

请查看http://www.rubydoc.info/github/bbatsov/RuboCop/RuboCop/NodePattern

看起来不错! :-) 请注意,如果您省略最后一个参数,MSG 将自动传递给 #add_offense - Drenmi
1
请注意,此处不包括使用安全导航符号的情况,例如 var&.unscoped。您需要添加一个单独的 on_csend(node) 来处理这种情况,并更新匹配器为: { (send ... :unscoped) (csend ... :unscoped) } - kooshywoosh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接