Search code examples
rubyprogram-flow

How to break out of begin block in Ruby?


How can I break out of the begin block and jump to the rescue block?

def function
  begin
    @document = Document.find_by(:token => params[:id])
    next if @document.sent_at < 3.days.ago # how can I skip to the rescue block here?
    @document.mark_as_viewed
  rescue
    flash[:error] = "Document has expired."
    redirect_to root_path
  end
end

My attempt using next doesn't work.


Solution

  • Well, you could raise an error. That's how begin/rescue blocks work. It's not a good idea, though - using error handling for business logic is generally frowned upon.

    It seems as though it would make much more sense to refactor as a simple conditional. Something like:

    def function
      @document = Invoice.find_by(:token => params[:id])
      if @document.sent_at < 3.days.ago
        flash[:error] = "Document has expired."
        redirect_to root_path
      else
        @document.mark_as_viewed 
      end
    end
    

    It seems as though you've confused a few different kinds of block-related keywords here:

    Error handling (begin/rescue/end) is for cases where you think something you try might raise an error, and respond in a particular way to it.

    next is for iteration - when you're looping through a collection and want to skip to the next element.

    Conditionals (if, unless, else, etc.) are the usual way for checking the state of something and executing different bits of code depending on it.