Search code examples
rubylintrubocop

Ruby, Prefer {...} over do...end for single-line blocks. But error


I have this code in a .rb Class file:

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

what I need is to remove do and end from the single line using, I think, the {}.

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

But I don't understand why it throws this error:

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

RuboCop version

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

Solution

  • To appease the Rubocop, switch either to this:

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

    Or this:

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

    I'd argue the former is a lot cleaner than the latter, but it's up to you.