user859999
user859999

Reputation:

Shortening a very long class definition in Ruby

I am woking on implementing Rubocop and I came across a line similar to this one in the codebase:

class ThisIsAVerlyLongClassName < JSONAPI::SomeOtherModule::AnotherClassWithAnInsaneName

Rubocop complains about the line length here, but I can't figure out a way to create a more compact version of this class definition, without renaming the classes, which is what I'm trying to avoid here.

Without going into a debate about coding style in general, 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?

Upvotes: 2

Views: 1530

Answers (4)

user859999
user859999

Reputation:

I just found out that a class definition can be split into multiple lines like so:

class ThisIsAVerlyLongClassName <
  JSONAPI::SomeOtherModule::AnotherClassWithAnInsaneName

It breaks syntax highlighting in Atom for the 2nd line, but the code runs and all tests pass!

Upvotes: 3

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369458

While class definition bodies have their own non-nested lexical scope (like method definition bodies), the superclass expression is evaluated within the containing scope. In other words: you can just use a local variable:

superclass = JSONAPI::SomeOtherModule::AnotherClassWithAnInsaneName
class ThisIsAVerlyLongClassName < superclass

Upvotes: 2

spickermann
spickermann

Reputation: 106852

You can usually disable a specific Rubocop warning on a specific line by adding a comment like the following to that line:

class A < B::C::D # rubocop:disable Metrics/LineLength

Upvotes: 2

Simone Carletti
Simone Carletti

Reputation: 176392

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?

There is no escape. If you want to fix that complain, you have to either:

  • disable it explicitly by setting an override in the .rubocop.yml or for that specific file
  • address the issue, hence rename the class

Upvotes: 1

Related Questions