Rubocop:在无效上下文中使用的文字。[Lint/Void]

Rubocop: Literal used in void context.[Lint/Void]

在我的 Ruby Rails 应用程序中进行 Rubocop 检查后,我在正确格式化下面的代码时遇到了一些问题。我不断收到错误消息:

Rubocop:Literal[:success, JSON.parse(response.to_str)] used in void context.[Lint/Void]

Rubocop:Literal[:unprocessable_entity, JSON.parse(response.to_str)] used in void context.[Lint/Void].

我只是不知道代码有什么问题以及如何解决它。

case response.code
when 200
  [:success, JSON.parse(response.to_str)]
  redirect_to root_url, notice: 'Logged in!'
when 422
  [:unprocessable_entity, JSON.parse(response.to_str)]
  flash.now[:alert] = 'Email or password is invalid'
  render 'new'
else
  raise "Invalid response #{response.to_str} received."
end

您没有在代码中的任何地方使用此 [:success, JSON.parse(response.to_str)] 和此 [:unprocessable_entity, JSON.parse(response.to_str)]。删除它或将其分配到变量中,但将其分配到变量中而不使用该变量可能会再次导致警告。

您应该删除不使用的代码。试试这个:

case response.code
when 200
  redirect_to root_url, notice: 'Logged in!'
when 422
  flash.now[:alert] = 'Email or password is invalid'
  render 'new'
else
  raise "Invalid response #{response.to_str} received."
end

或者试试这个:

case response.code
when 200
  @success = [:success, JSON.parse(response.to_str)]
  redirect_to root_url, notice: 'Logged in!'
when 422
  @error = [:unprocessable_entity, JSON.parse(response.to_str)]
  flash.now[:alert] = 'Email or password is invalid'
  render 'new'
else
  raise "Invalid response #{response.to_str} received."
end

让我知道它是否有效。