Search code examples
ruby-on-railsrubocop

How do I bypass Only use parentheses for ternary expressions with complex conditions?


My code looks like this:

def redirector
  # :nocov:
  unless ENV["URL"]
    return "https://google.com"
  end
  # :nocov:

  redirect_url = (request.original_fullpath.include? "404") ? root_path : request.original_url
  param_object = { redirect: redirect_url }

  ENV["URL"] + "?" + param_object.to_param
end

Is there a better way to write this?

redirect_url = (request.original_fullpath.include? "404") ? root_path : request.original_url

Solution

  • You can write it like this:

    redirect_url = request.original_fullpath.include?("404") ? root_path : request.original_url
    

    Or even:

    redirect_url = if request.original_fullpath.include? "404"
      root_path
    else
      request.original_url
    end
    

    You get the warning about parentheses, because your condition is simple. Complex condition would look like this:

    foo = (bar && baz) ? a : b
    

    Check out the doc.