如何配置RuboCop仅检查特定类CustomController的notify方法调用?
如何用RuboCop禁止特定类及其子类的notify方法调用
核心思路
RuboCop没有内置的直接匹配器来检查方法调用的类上下文,但可以通过自定义Cop实现需求——核心逻辑是:识别notify的无接收者调用,再向上遍历AST确认当前类是否继承自CustomController(包括子类)。
自定义Cop实现
创建自定义Cop文件(比如lib/rubocop/cop/custom/forbid_custom_controller_notify.rb),代码如下:
# frozen_string_literal: true module RuboCop module Cop module Custom class ForbidCustomControllerNotify < Base MSG = '禁止使用CustomController及其子类的notify方法' # 匹配无接收者的notify调用,比如notify('test') def on_send(node) return unless node.method?(:notify) && node.receiver.nil? # 向上查找当前方法所在的类节点 class_node = node.each_ancestor(:class).first return unless class_node # 检查类是否继承自CustomController(包括子类) if inherits_from_custom_controller?(class_node) add_offense(node) end end private def inherits_from_custom_controller?(class_node) # 获取类的继承链 ancestor_classes = class_node.each_ancestor(:class).to_a ancestor_classes.unshift(class_node) ancestor_classes.any? do |ancestor| superclass = ancestor.parent_class next false unless superclass # 匹配直接继承CustomController,或者递归检查父类的继承关系 superclass.const_name == 'CustomController' || inherits_from_custom_controller?(superclass) end rescue NameError false end end end end end
配置启用
在项目的.rubocop.yml中添加配置,启用这个自定义Cop:
Custom/ForbidCustomControllerNotify: Enabled: true Include: - 'app/controllers/**/*.rb' # 根据你的代码路径调整范围
逻辑说明
- 节点匹配:
on_send方法只处理无接收者的notify调用(对应node.method?(:notify) && node.receiver.nil?),避免误匹配其他对象的notify调用。 - 上下文查找:通过
each_ancestor(:class)向上遍历AST,定位当前调用所在的类定义节点。 - 继承链检查:
inherits_from_custom_controller?递归遍历类的继承链,只要某个父类是CustomController,就判定为需要禁止的调用。
这套逻辑能精准匹配MatchClass中的notify调用,同时忽略NotMatchClass里的同名方法。
内容的提问来源于stack exchange,提问作者ryush00
相关产品推荐
相关产品推荐

