0

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
mu is too short
  • 426,620
  • 70
  • 833
  • 800
user2012677
  • 5,465
  • 6
  • 51
  • 113
  • 2
    You can always [change the maximum line length](https://stackoverflow.com/a/37228672/3784008) in your configuration. I always set it to 120 or higher. 80 characters is absurd. – anothermh Sep 05 '19 at 17:21

2 Answers2

2

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
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
1

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.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77