Ruby Standard - Ruby 风格标准

huacnlee · March 05, 2021 · Last by daqing replied at March 11, 2021 · 1488 hits

以前大家可能都在用 Rubocop,但实际上 Rubocop 没有标准的,并且 Rubycop 默认的规则还特别不受社区待见,比如 Rails,绝大多数项目都会又一个自己的 .rubocop.yml

我也是在我的各种项目里面都有单独的 .rubocop.yml 来覆盖默认的 Rubocop 规则,尤其是其中“单引号”规则,及其讨厌。

关于单引号 or 双引号的问题,也有过 Issue 讨论,作者和主要贡献者认为此项依然有争议,于是问题搁置的。

实际上从 统计情况 来看,社区的著名项目几乎(也包括各种热门 Gem 比如:Devise、Doorkeeper、CarrierWave 以及 Rails)他们都在使用双引号。

于是有人认为我们可能需要一套标准了。

Standard Ruby 1.0

https://blog.testdouble.com/posts/2021-03-04-announcing-standard-ruby-1.0/

Matz 还亲自发帖推荐

https://twitter.com/yukihiro_matz/status/1367646746650628098

项目地址

https://github.com/testdouble/standard

重点特性

不需要配置,以后都是统一的标准。

  • 2 spaces – for indentation
  • Double quotes for string literals - because pre-committing to whether you'll need interpolation in a string slows people down
  • 1.9 hash syntax - When all the keys in a hash literal are symbols, Standard enforces Ruby 1.9's {hash: syntax}
  • Braces for single-line blocks - Require {/} for one-line blocks, but allow either braces or do/end for multiline blocks. Like using do/end for multiline blocks? Prefer {/} when chaining? A fan of expressing intent with Jim Weirich's semantic block approach? Standard lets you do you!
  • Leading dots on multi-line method chains - chosen for these reasons.
  • Spaces inside blocks, but not hash literals - In Ruby, the { and } characters do a lot of heavy lifting. To visually distinguish hash literals from blocks, Standard enforces that (like arrays), no leading or trailing spaces be added to pad hashes And a good deal more

效果演示

我用 Homeland 试了一下,下面是一些特别变化的地方:

-        render json: { ok: 1 }
+        render json: {ok: 1}

{} 在 Hash 的时候,将会去掉左右的空格,这个场景,可能我需要一段时间适应,我们在 Go 里面也是左右带空格的,它这么定义估计是保持和 []() 一致。

- scope :popular, -> {where("likes_count > 5")}
+ scope :popular, -> { where("likes_count > 5") }

{} 在 Block 的场景,左右空格依然还保留的。

不需要配置是最重要的特性!争论代码风格很浪费时间,什么标准都好,有一个就行。

Reply to Rei

是的,只要团队对代码风格有共识,坚持贯彻就好了。

这哥们在 18 年 RubyConf 上分享过,挺搞笑的

"What if I don't like a rule?"

"Humans are very adaptable."

😀 看上去挺好的耶

挺好,应该采用

You need to Sign in before reply, if you don't have an account, please Sign up first.