Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Rubocop - Begin + Rescue syntax

I have the following code:

  def payload
    begin
      @payload ||= Warden::JWTAuth::TokenDecoder.new.call(token)
    rescue JWT::ExpiredSignature => e
      Rollbar.warning(e)
    end
  end

From brief reading of a few blogs I'm supposed to be using begin rescue and end to handle the error as I'm doing above, however I'm getting a redundant 'begin' rubocop warning.

Is begin only used when specifying a bit of code that may cause an error within a larger block? And is it therefore redundant here?

Thanks in advance

EDIT: And if I don't need it, is it written as

  def payload
    @payload ||= Warden::JWTAuth::TokenDecoder.new.call(token)
  rescue JWT::ExpiredSignature => e
    Rollbar.warning(e)
  end

?

like image 994
Mark Avatar asked Jan 11 '19 09:01

Mark


2 Answers

Do this when the begin would be the first thing in your method

def payload
  @payload ||= Warden::JWTAuth::TokenDecoder.new.call(token)
rescue JWT::ExpiredSignature => e
  Rollbar.warning(e)
end
like image 83
Ursus Avatar answered Oct 19 '22 00:10

Ursus


Method bodies, block bodies, and lambda bodies are implicit exception blocks. You don't need to wrap the entire code of a method body, block body, or lambda body in a begin / rescue / else / ensure / end exception block, since it is already implicitly one. So, whenever you have something like

def foo
  begin
  rescue
  end
end

or

foo do
  begin
  rescue
  end
end

or

-> do
  begin
  rescue
  end
end

you can replace it with just

def foo
rescue
end

or the equivalent for blocks and lambdas.

like image 33
Jörg W Mittag Avatar answered Oct 19 '22 01:10

Jörg W Mittag