You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写RuboCop自定义Cop检测单行类定义并规范格式?

编写RuboCop自定义Cop识别单行类定义并自动修正

要实现识别MyError = Class.new(StandardError)这类单行类定义并替换为标准class语法的Cop,按以下步骤操作:

1. 创建自定义Cop文件

在项目中新建lib/rubocop/cop/custom/single_line_class_def.rb,代码如下:

# frozen_string_literal: true

module RuboCop
  module Cop
    module Custom
      # 识别形如 `MyError = Class.new(StandardError)` 的单行类定义,
      # 建议格式化为 `class MyError < StandardError; end`
      class SingleLineClassDef < Base
        MSG = '使用 `class %<const>s < %<parent>s; end` 替代单行类赋值写法'
        RESTRICT_ON_SEND = %i[new].freeze

        def on_send(node)
          # 只处理 Class.new 的调用
          return unless node.receiver&.const_type? && node.receiver.short_name == :Class
          return unless node.method?(:new)

          # 定位上层的赋值节点(常量、局部变量等赋值场景)
          assignment_node = node.parent
          return unless assignment_node&.assignment?

          # 提取要定义的类名和父类节点
          const_node = assignment_node.children.first
          parent_class_node = node.first_argument

          # 仅处理常量赋值(错误类通常用常量)且有明确父类的情况
          return unless const_node&.const_type? && parent_class_node

          add_offense(node, message: format(MSG, const: const_node.short_name, parent: parent_class_node.source)) do |corrector|
            # 生成标准class语法并替换原代码
            corrected_code = "class #{const_node.short_name} < #{parent_class_node.source}; end"
            corrector.replace(assignment_node, corrected_code)
          end
        end
      end
    end
  end
end

2. 配置RuboCop

在项目根目录的.rubocop.yml中启用这个Cop:

Custom/SingleLineClassDef:
  Enabled: true
  # 可选:添加需要忽略的文件路径
  # Exclude:
  #   - vendor/**/*

3. 运行与自动修正

执行RuboCop检查:

rubocop --require ./lib/rubocop/cop/custom/single_line_class_def.rb

如果需要自动修正不符合规范的代码,加上-a参数:

rubocop -a --require ./lib/rubocop/cop/custom/single_line_class_def.rb

关键细节说明

  • RESTRICT_ON_SEND:限定只监听new方法调用,减少不必要的节点遍历,提升性能
  • 常量类型判断:只处理const_type?的赋值节点,避免误判局部变量的类似写法
  • 兼容任意父类:不管父类是StandardError还是ActiveRecord::Base,都能正确生成标准class语法
  • 自动修正逻辑:直接替换整个赋值节点,确保代码格式统一

内容的提问来源于stack exchange,提问作者Igor_Marques

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 16:04:54