在 Ruby 中缩短很长的 class 定义
Shortening a very long class definition in Ruby
我正在着手实施 Rubocop,我在代码库中遇到了与这一行类似的行:
class ThisIsAVerlyLongClassName < JSONAPI::SomeOtherModule::AnotherClassWithAnInsaneName
Rubocop 抱怨这里的行长度,但我想不出一种方法来创建这个 class 定义的更紧凑版本,而不重命名 classes,这就是我尽量避开这里。
在不讨论一般的编码风格的情况下,让 Rubocop 停止抱怨行长度而不在 .rubocop.yml 中制造例外或编辑 class 的最佳方法是什么和模块名称?
what is the best way to get Rubocop to stop complaining about the line length without making an exception in .rubocop.yml or editing the class and module names?
无路可逃。如果你想解决这个问题,你必须:
- disable it explicitly 通过在 .rubocop.yml 或特定文件中设置覆盖
- 解决问题,因此重命名 class
您通常可以通过向该行添加如下注释来禁用特定行上的特定 Rubocop 警告:
class A < B::C::D # rubocop:disable Metrics/LineLength
虽然 class 定义主体有自己的非嵌套词法作用域(如方法定义主体),但 superclass 表达式在包含作用域内求值。换句话说:你可以只使用局部变量:
superclass = JSONAPI::SomeOtherModule::AnotherClassWithAnInsaneName
class ThisIsAVerlyLongClassName < superclass
我刚刚发现 class 定义可以像这样分成多行:
class ThisIsAVerlyLongClassName <
JSONAPI::SomeOtherModule::AnotherClassWithAnInsaneName
它破坏了 Atom 中第 2 行的语法突出显示,但代码运行并且所有测试都通过了!
我正在着手实施 Rubocop,我在代码库中遇到了与这一行类似的行:
class ThisIsAVerlyLongClassName < JSONAPI::SomeOtherModule::AnotherClassWithAnInsaneName
Rubocop 抱怨这里的行长度,但我想不出一种方法来创建这个 class 定义的更紧凑版本,而不重命名 classes,这就是我尽量避开这里。
在不讨论一般的编码风格的情况下,让 Rubocop 停止抱怨行长度而不在 .rubocop.yml 中制造例外或编辑 class 的最佳方法是什么和模块名称?
what is the best way to get Rubocop to stop complaining about the line length without making an exception in .rubocop.yml or editing the class and module names?
无路可逃。如果你想解决这个问题,你必须:
- disable it explicitly 通过在 .rubocop.yml 或特定文件中设置覆盖
- 解决问题,因此重命名 class
您通常可以通过向该行添加如下注释来禁用特定行上的特定 Rubocop 警告:
class A < B::C::D # rubocop:disable Metrics/LineLength
虽然 class 定义主体有自己的非嵌套词法作用域(如方法定义主体),但 superclass 表达式在包含作用域内求值。换句话说:你可以只使用局部变量:
superclass = JSONAPI::SomeOtherModule::AnotherClassWithAnInsaneName
class ThisIsAVerlyLongClassName < superclass
我刚刚发现 class 定义可以像这样分成多行:
class ThisIsAVerlyLongClassName <
JSONAPI::SomeOtherModule::AnotherClassWithAnInsaneName
它破坏了 Atom 中第 2 行的语法突出显示,但代码运行并且所有测试都通过了!