如何绕过仅使用圆括号表示复杂条件的三元表达式?

时间:2018-02-13 17:51:10

标签: ruby-on-rails rubocop

我的代码如下所示:

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

有没有更好的方法来写这个?

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

1 个答案:

答案 0 :(得分:2)

你可以这样写:

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

甚至:

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

你得到关于括号的警告,因为你的情况很简单。复杂的情况看起来像这样:

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

Check out the doc