【问题标题】:Ruby, Prefer {...} over do...end for single-line blocks. But errorRuby,对于单行块,更喜欢 {...} 而不是 do...end。但是错误
【发布时间】:2017-12-28 18:03:00
【问题描述】:

我在 .rb 类文件中有这段代码:

field :user, Types::UserType do resolve ->(_obj, _args, ctx) { ctx[:user] } end

我需要的是使用 {} 从单行中删除 doend

[Style/BlockDelimiters] Prefer{...}overdo...endfor single-line blocks.

但我不明白为什么会抛出这个错误:

[ruby] syntax error, unexpected '{', expecting '('
[ruby] syntax error, unexpected '}', expecting keyword_end

RuboCop 版本

$ rubocop -V
0.51.0 (using Parser 2.4.0.2, running on ruby 2.4.2 x64-mingw32)

【问题讨论】:

  • “我需要的是删除”——你不需要盲目地遵循 rubocop 一开始所说的一切。如果您仍然想满足它,请正确管理运算符优先级,可能在 Types::UserType 周围加上括号。
  • @mudasobwa 我认为它会围绕整个参数列表,例如field(:user, Types::UserType) do #etc 据说 2 行或使用更自然的内联块语法会更好。
  • field(:user, Types::UserType) { resolve ->(_obj, _args, ctx) { ctx[:user] } }
  • @engineersmnky,more natural inline block syntax 是什么?
  • 见@gabrielhilal 评论。使用花括号{...} 来表示内联块更自然(阅读惯用语)。内部解析器不允许使用 do...end 作为内联块,它通常不被认为是正确的样式

标签: ruby lint rubocop


【解决方案1】:

为了安抚 Rubocop,请切换到此:

field :user, Types::UserType do
  resolve ->(_obj, _args, ctx) { ctx[:user] }
end

或者这个:

field(:user, Types::UserType) { resolve ->(_obj, _args, ctx) { ctx[:user] } }

我认为前者比后者干净得多,但这取决于你。

【讨论】:

  • @engineersmnky 我的立场是正确的。我想知道他们什么时候解决的。大概是 1.9。
  • @engineersmnky 相同。也许我将此与语法的其他一些怪癖混淆了。我已经更新了答案。
  • 后者在2.4上无效。
  • 这可能是由于那里的绑定不明确,不清楚该块是提供给Types::UserType 还是field。我已经用有效的语法更新了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 2016-09-24
  • 2010-09-24
  • 2011-05-13
相关资源
最近更新 更多