【问题标题】:Rubocop line length too long, how do I shorten given line?Rubocop 线长度太长,如何缩短给定线?
【发布时间】:2020-01-08 13:51:46
【问题描述】:

Rubocop 告诉我我的行太长了。如何在不破坏代码的情况下修复这样的行上的格式?允许您使用下一行的规则是什么?

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

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

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-5.2 rubocop


【解决方案1】:

在很多地方,在 Ruby 中插入换行符是合法的。例如你的第一个 sn-p:

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

您的第二个 sn-p 根本没有意义。一个对象总是知道它自己的类,从来没有一个对象检查它自己的类的理由。这不仅仅是代码异味或反模式,这是一个巨大的危险信号,该代码的作者不了解面向对象和继承。

第二个 sn-p 应该使用Replace Conditional with Polymorphism Refactoring 重构。您没有显示足够的代码来确切了解如何操作,但我建议您这样做:

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

【讨论】:

    【解决方案2】:

    我会这样写:

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

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

    请注意,“您应该内联 if 语句”的 rubocop 规则不适用,因为这样做会使行太长。

    【讨论】:

      猜你喜欢
      • 2016-09-10
      • 1970-01-01
      • 2013-12-07
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多