简体   繁体   中英

Rubocop line length too long, how do I shorten given line?

Rubocop is telling me my line length is too long. How do I fix the formatting on a line like these without my code breaking? What are the rules that allow you to use the next line?

  belongs_to :car, -> { includes(:listable).where(listings: {listable_type: Car.to_s}) }, foreign_key: :listable_id

and

  raise ArgumentError, "Can only initiate inherited Classes of Base, not Base Directly" if self.class == Registration::Base

There are lots of places where it is legal to insert newlines in Ruby. For example your first snippet:

belongs_to(
  :car,
  -> {
    includes(
      :listable
    )
    .where(
      listings:
        {
          listable_type:
            Car
            .to_s
        }
    )
  },
  foreign_key:
    :listable_id
)

Your second snippet simply doesn't make sense. An object always knows its own class, there is never ever a reason for an object to check its own class. That is not just a code smell or an anti-pattern, that is a huge red flag that the author of that code has no understanding of object-orientation and inheritance.

The second snippet should be refactored using the Replace Conditional with Polymorphism Refactoring . You don't show enough code to see exactly how, but I would suggest something like this:

class Registration::Base
  def initialize
    raise ArgumentError, 'Can only initiate inherited Classes of Base, not Base Directly' 
  end
end

Here's how I would write it:

belongs_to :car,
  -> { includes(:listable).where(listings: {listable_type: Car.to_s}) },
  foreign_key: :listable_id

and

if self.class == Registration::Base
  raise ArgumentError, 'Can only initiate inherited Classes of Base, not Base Directly'
end

Note that the rubocop rule for "You should inline if statements" does not apply when doing so would make the line too long.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM