如何拆分Ruby的长行

tv6aics1  于 2023-06-22  发布在  Ruby
关注(0)|答案(4)|浏览(116)

我总是在我的Rails models的顶部得到很大的代码行。我正在寻找最好的方法来打破他们的建议与标准的Ruby风格。例如,我现在看到的一行是这样的:

delegate :occupation, :location, :picture_url, :homepage_url, :headline, :full_name, :to => :profile, :prefix => true, :allow_nil => true

拆分这些长方法调用行的常规方式是什么?

yh2wf1be

yh2wf1be1#

简单的回答是这取决于

基础知识

首先,你可以使用“新的”Ruby哈希语法来保存一些字符:

result = very_long_method_name(something: 1, user: user, flange_factor: 1.34)

对比

result = very_long_method_name(:something => 1, :user => user, :flange_factor => 1.34)

哈希/数组

有时候你需要初始化一个数组或哈希,特别是对于哈希,这样写很好:

args = {
  first_name: "Aldo",
  email: "nospam@mail.example.com",
  age: Float::INFINITY
}

在同一行上的相同哈希将是(不那么好):

args = {first_name: "Aldo", email: "nospam@mail.example.com", age: Float::INFINITY}

各种方法调用

有些方法需要很多参数,或者这些参数有很长的名字:

%table
  %thead
    %th
      %td= t("first_name", scope: "activemodel.lazy_model.not_so_active_model", some_interpolation_argument: "Mr.", suffix: "(Jr.)")

在这种情况下,我可能会这样写:

%table
  %thead
    %th
      %td= t("first_name",
             scope: "activemodel.lazy_model.not_so_active_model",
             some_interpolation_argument: "Mr.",
             suffix: "(Jr.)")

它仍然不是很漂亮,但我想它没有那么丑。

class person < ActiveRecord::Base
  validates :n_cars, numericality: {
                       only_integer: true,
                       greater_than: 2,
                       odd: true,
                       message: t("greater_than_2_and_odd",
                                  scope: "activerecord.errors.messages")
                     }
end

再说一遍,不是地球上最漂亮的代码,但它有某种结构。
此外,有时您可以使用变量来拆分行。这只是一个例子,但基本上你命名的东西块(有时在此之后,你意识到你实际上可以移动块在一个方法)

class person < ActiveRecord::Base
  NUMERICALITY_OPTS = {
    only_integer: true,
    greater_than: 2,
    odd: true,
    message: t("greater_than_2_and_odd", scope: "activerecord.errors.messages")
  }
  validates :n_cars, numericality: NUMERICALITY_OPTS
end

区块

闭包(Closes):

User.all.map { |user| user.method_name }

可以这样写:

User.all.map(&:method_name)

如果你有合适的块,尝试使用do-end而不是花括号:

nicotine_level = User.all.map do |user|
  user.smoker? ? (user.age * 12.34) : 0.1234
end

条件

不要在复杂的事情中使用三元if运算符:

nicotine_level = user.smoker? ? (user.age * 1.234 + user.other_method) : ((user.age - 123 + user.flange_factor) * 0)

if user.smoker?
  nicotine_level = user.age * 1.234 + user.other_method
else
  nicotine_level = (user.age - 123 + user.flange_factor) * 0
end

如果你有像这样复杂的if语句:

if user.vegetarian? && !user.smoker? && (user.age < 25) && (user.n_girlfriends == 0) && (user.first_name =~ /(A|Z)[0-1]+/)
end

在方法中移动内容,使内容不仅更短,而且可读性更好:

if user.healthy? && user.has_a_weird_name?
  # Do something
end

# in User
def healthy?
  vegetarian? && !smoker? && (age < 25) && (n_girlfriends == 0)
end

def user.has_a_weird_name?
  user.first_name =~ /(A|Z)[0-1]+/
end

长字符串

Heredoc是你的朋友...我总是需要谷歌,以获得正确的语法,但一旦你得到它的权利是使某些事情更好地阅读:

execute <<-SQL
  UPDATE people
  SET smoker = 0
  OK, this is a very bad example.
SQL

查询

对于简单的情况,我倾向于这样做:

# Totally random example, it's just to give you an idea
def cars_older_than_n_days(days)
  Car.select("cars.*, DATEDIFF(NOW(), release_date) AS age")
     .joins(:brand)
     .where(brand: {country: "German"})
     .having("age > ?", days)
end

有时候查询更糟糕。如果我使用squeel并且查询很大,我倾向于使用括号,如下所示:

# Again, non-sense query
Person.where {
  first_name = "Aldo" |
  last_name = "McFlange" |
  (
    age = "18" &
    first_name = "Mike" &
    email =~ "%@hotmail.co.uk"
  ) |
  (
    person.n_girlfriends > 1 &
    (
      country = "Italy" |
      salary > 1_234_567 |
      very_beautiful = true |
      (
        whatever > 123 &
        you_get_the_idea = true 
      )
    )
  )
}

我会说,如果可能的话,尽量避免复杂的查询,并将它们拆分到较小的范围内或其他:

scope :healthy_users, lambda {
  younger_than(25).
  without_car.
  non_smoking.
  no_girlfriend
}

scope :younger_than, lambda { |age|
  where("users.age < ?", age)
}

scope :without_car, lambda {
  where(car_id: nil)
}

scope :non_smoking, lambda {
  where(smoker: false)
}

scope :no_girlfriend, lambda {
  where(n_girlfriends: 0)
}

这可能是最好的办法。

现实

不幸的是,人们倾向于写很长的行,这是不好的:

  • 很长的行很难阅读(如果印刷书籍没有超大的页面,这是有原因的)
  • 确实,我们大多使用2个屏幕,但是当从控制台使用git diff之类的东西时,有很长的线路是痛苦的
  • 有时候,您在屏幕较少的13英寸笔记本电脑上工作
  • 即使我喜欢使用2个屏幕,我也喜欢将编辑器拆分为同时编辑2个文件-长行迫使我使用水平滚动条(地球上最讨厌的事情)
  • 是的,你可以在你的编辑器中启用自动换行,但它仍然没有那么好(恕我直言)

我的编辑器里有一把尺子,这样我就能知道什么时候我会越过第80个字符。但很少越过几个字符的线,这实际上比分裂它更好。

总结

有几种方法可以保持80年代以下的线路,通常取决于情况。长行的问题不仅仅是糟糕的风格,长行通常是太复杂的症状

fcg9iug3

fcg9iug32#

沿着如下的东西:

delegate :occupation, :location, :picture_url, 
         :homepage_url, :headline, :full_name, 
         :to => :profile, :prefix => true, :allow_nil => true

或者,如果你想突出选项哈希(一个合理的事情):

delegate :occupation, :location, :picture_url, 
         :homepage_url, :headline, :full_name, 
     :to => :profile, :prefix => true, :allow_nil => true

把所有这些都放在一行上的想法让我觉得是一个糟糕的想法,这意味着你必须滚动任意的数量才能看到被委派的内容。真恶心
我可能也会把东西排成一行,也许按字母顺序排列。

delegate :full_name, :headline,   :homepage_url,
         :location,  :occupation, :picture_url,
     :to => :profile, :prefix => true, :allow_nil => true

如果文件没有太多/任何其他实质性内容,我可能会将每个方法符号放在自己的行中,只是为了使编辑更容易。在一个更大的文件中,我不想占用空间。

  • 编辑2022:我可能会把每个符号放在自己的一行,包括选项。从长远来看,这只是更容易处理,我变得更懒了。

我从没想过这种事。

  • 编辑 * 我想我做:/

这些天来,我可能会根据“相似性”对委托方法进行分组,大致如下:

delegate :full_name, :headline,
         :location,  :occupation,
         :homepage_url, :picture_url,
     to: :profile, 
     prefix: true, 
     allow_nil: true

当值也是一个符号时,我的陪审团坚持1.9的哈希语法;我觉得很好笑。我也不确定要缩进到哪里--在IDE重新格式化时可能会丢失它,但如果我使用新语法,我会喜欢上面的样子。

6rvt4ljy

6rvt4ljy3#

虽然这个问题已经有了两个很好的答案,但我还是想让未来的读者参考Ruby Style Guide来解决这些问题。
目前,源代码布局部分有大量关于如何在各种情况下断行的信息:

# starting point (line is too long)
def send_mail(source)
  Mailer.deliver(to: 'bob@example.com', from: 'us@example.com', subject: 'Important message', body: source.text)
end

# bad (double indent)
def send_mail(source)
  Mailer.deliver(
      to: 'bob@example.com',
      from: 'us@example.com',
      subject: 'Important message',
      body: source.text)
end

# good
def send_mail(source)
  Mailer.deliver(to: 'bob@example.com',
                 from: 'us@example.com',
                 subject: 'Important message',
                 body: source.text)
end

# good (normal indent)
def send_mail(source)
  Mailer.deliver(
    to: 'bob@example.com',
    from: 'us@example.com',
    subject: 'Important message',
    body: source.text
  )
end
# bad - need to consult first line to understand second line
one.two.three.
  four

# good - it's immediately clear what's going on the second line
one.two.three
  .four

它通常被证明是一个“解决方案”,用于过于复杂的代码,正如@Aldo已经提到的:

# bad
some_condition ? (nested_condition ? nested_something : nested_something_else) : something_else

# good
if some_condition
  nested_condition ? nested_something : nested_something_else
else
  something_else
end
d7v8vwbk

d7v8vwbk4#

从我的经验来看,似乎惯例实际上并不是要打破线路。我见过的大多数项目,包括rails本身的代码库,似乎都不存在很长的不间断行的问题。
所以我想说,如果你想遵循惯例,就不要打断队伍。如果你决心打破界限,那么就没有广泛遵循的惯例。您可以使用您喜欢的任何编码风格。

相关问题