Rubocop: Rails - rubocop doesn't like syntax for model scopes

Created on 17 Jul 2013  路  10Comments  路  Source: rubocop-hq/rubocop

In my rails app, I have scopes that use the following syntax:

scope :foo, lambda { |f|
  where(condition: "value")
}

And when I rubocop my models, I get C: Avoid using {...} for multi-line blocks.

When I replace the {...} form with a do..end form, my scopes don't work.

Most helpful comment

Ah, yes - {} binds more tightly than do..end and in the second case the code is interpreted as:

scope(:foo, lambda) do |f|
  where(condition: 'value')
end

@jonas054 Will you please take care of this bug?

All 10 comments

Ah, yes - {} binds more tightly than do..end and in the second case the code is interpreted as:

scope(:foo, lambda) do |f|
  where(condition: 'value')
end

@jonas054 Will you please take care of this bug?

As well, also this case:

expect { do_something }.to raise_error(ErrorClass) { |error|
  # ...
}

@bbatsov @yujinakayama Yes. But how do we want RuboCop to act in these cases? Should it conclude that changing the braces to do..end and adding parentheses to overcome the difference in binding would give awkward code? My initial reaction is that the inspected code should be changed to

scope :foo, (lambda do |f|
               where(condition: 'value')
             end)

and

expect { do_something }.to(raise_error(ErrorClass) do |error|
                             # ...
                           end)

respectively.

I was thinking about making RuboCop accept {..} if changing it to do..end leads to a different meaning of the syntax. Anyway I think most users don't accept such awkward codes, since DSL is a beautiful part of Ruby.

That makes sense. I'll try to implement it.

@jonas054 I'm still experiencing this in RuboCop 0.27.1. Is this fixed?

@deivid-rodriguez Are you really? We're checking a few cases in the spec for the Blocks cop. See https://github.com/bbatsov/rubocop/blob/master/spec/rubocop/cop/style/blocks_spec.rb#L52-L66

Do you have some example code where RuboCop still reports braces that actually can't be changed to do..end?

Not actually, my bad. Don't know why I thought the resolution was allowing the -> syntax in the ambiguous cases. Just reread this issue and I really don't know where I got that idea from... Again, sorry.

@jonas054 I am still experiencing this. I ran this through the code for https://github.com/VisitMeet/visitmeet and it showed me the error everyone is having here.

@bishisht Please open a new issue with the details of your problem.

Was this page helpful?
0 / 5 - 0 ratings