rubocop: AndOr sees `render and return` as a violation

How can I configure RuboCop to no longer see the code below as a violation to the AndOr check?

render nothing: true, status: :bad_request and return

Currently it tells me to replace and with &&, which is not correct as far as I know.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 8
  • Comments: 17 (4 by maintainers)

Most upvoted comments

This conflicts with the current Rails guides, meaning this issue should probably be reopened.

Make sure to use and return instead of && return because && return will not work due to the operator precedence in the Ruby Language. http://guides.rubyonrails.org/layouts_and_rendering.html#avoiding-double-render-errors

If your intention is to always return and you’re using and as a more visually pleasing alternative to ;

This is not the case. I agree, if your intention is to always return then yes, use ;. Otherwise you have some kind of expectation from the left-hand side and you can use and/or to do something:

pass_or_fail and "it passed"
pass_or_fail or "it failed"
pass_or_fail ; "unknown"

That’s a trivial example which can easily be replaced with if/unless but I hope it illustrates that ; is not and.

It’s true that the intention for render is to always return. But by using ; you’re not chaining the operations together. This is evident if you have a conditional:

some_conditional = false
render 'new' ; return if some_conditional
# ...
render 'form' # double render

I don’t think it’s fair to call and return a hack or a workaround. Sure and/or can cause developers grief when used in a conditional, but I think they have a place when used as flow control operators (as in the case of and return). I’ve always had the impression that and return was considered idiomatic Ruby.

def create
  ...
  render('thanks') && return if @person.save
end

Or

def create
  ...
  (render 'thanks') && return if @person.save
end

Part of the problem here is that the Rails community have decided that the and operator has different semantics than that which the and operator was originally intended for. Whereas && is still viewed as the logical and, and has come to mean ‘do something and then do something else’.

@uri It depends. If your intention is to always return and you’re using and as a more visually pleasing alternative to ;, depending on the left hand side to always return a truthy value, then I think it’s an ugly hack. @mikegee said this earlier in the discussion.

Where would the parens go in this case?

I prefer to put the return on the next line. I’m not sure why and return became ok after render & redirect_to in the Rails community. It looks like a hack to me.

Also, I think render nothing: true, status: :bad_request is the same as head :bad_request.