ruby-on-railsrubyinstance-method

How to use Rails instance public method performed? in if-else


How does one use the Ruby on Rails method performed? in an if else statement?

I tried to use this StackOverflow anwser in my example below:

if condition
  does something
elsif redirect_to(records_path)
  performed?
  does another thing
else
  yet another thing
end

But this only redirects without checking if it is performed.

I want it to check if the redirect to records_path is performed and when true do something (or "does another thing" in my example)

I also tried this:

elseif records_path.performed?

And this:

elseif redirect_to(records_path) performed?()

And all things in between.

Can somebody explain how it's done and how I could've get it from the docs?


Solution

  • In a controller action, when we type render or redirect_to those are not immediately executed, but they are queued and will be executed after the completion of the method. So this allows to have double renders or redirect_to in a controller action, and this will generate an error (because then rails has no idea which to execute). So that is why in rails they have added a method performed? which will indicate if a render or redirect_to has already been called (queued) or not.

    In most cases this is not really needed because normally your controller code is pretty simple.

    To clarify: performed? does not actually test the redirect_to has been done, it just tests a render or redirect-to was called/queued. Furthermore the redirect_to does not return a boolean indicating whether it was done or not.

    So your code should be like this:

    if condition
      does something
    else 
      redirect_to(records_path)
    end 
    if performed?
      # the redirect-to was executed
      does another thing # but not a render or redirect
    else
      yet another thing 
      # and could be a render or redirect 
      # if not the normal view will be rendered
    end
    

    Please not that in this simple example the performed? is just the negative of condition so you could easily squash those together.