Ruby Actions: How to avoid a bunch of returns to halt execution?

Posted by Alexandre on Stack Overflow See other posts from Stack Overflow or by Alexandre
Published on 2010-03-13T22:43:59Z Indexed on 2010/03/13 22:45 UTC
Read the original article Hit count: 348

How can I DRY the code below? Do I have to setup a bunch of ELSEs ? I usually find the "if this is met, stop", "if this is met, stop", rather than a bunch of nested ifs.

I discovered that redirect_to and render don't stop the action execution...

def payment_confirmed    
  confirm_payment do |confirmation|    
    @purchase = Purchase.find(confirmation.order_id)
    unless @purchase.products_match_order_products?(confirmation.products)
      # TODO notify the buyer of problems
      return
    end

    if confirmation.status == :completed
      @purchase.paid!                     
      # TODO notify the user of completed purchase
      redirect_to purchase_path(@purchase)
    else      
      # TODO notify the user somehow that thigns are pending
    end   

    return
  end

  unless session[:last_purchase_id]
    flash[:notice] = 'Unable to identify purchase from session data.'
    redirect_to user_path(current_user) 
    return
  end

  @purchase = Purchase.find(session[:last_purchase_id]) 

  if @purchase.paid?
    redirect_to purchase_path(@purchase)       
    return
  end

  # going to show message about pending payment
end

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about actionview