Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine whether a controller action has rendered (rather than redirected?)

The performed? method returns true in a controller if the application has redirected or rendered.

How can I determine whether the application rendered (rather than redirected)?

Judging from the performed? docs, I can look at @performed_render, but this seems hacky.

Edit: Why do I want to do this?

I'm trying to cache the output of a controller action only in the case that it results in a render (and not a redirect). Here's the code I'm using now: (based on render-caching)

  def render_with_cache(options = {})
    key = ([request.request_uri, request.format] | (options.delete(:key_additions) || [])).join("::")
    body = Rails.cache.read(key)

    if body
      render :text => body
    else
      yield if block_given?
      render unless performed?
      if @performed_render
        Rails.cache.write(key, response.body, options) # :expires_in
      end
    end
  end
like image 404
Tom Lehman Avatar asked Jan 24 '10 22:01

Tom Lehman


People also ask

What is difference between render and redirect?

Render tells Rails which view or asset to show a user, without losing access to any variables defined in the controller action. Redirect is different. The redirect_to method tells your browser to send a request to another URL.

What is head in ruby on Rails?

In Rails, the head method is shorthand for "respond only with this status, headers, and an empty body." The head method takes a symbol corresponding to a status, in this case :no_content for "204."


1 Answers

Rails 3.2+ now uses a method called performed? for determining whether or not a render or redirect has already been performed.

Contrived example:

def index
  redirect_to not_found_path unless authenticated?
  render action: "show_all" unless performed?
end
like image 126
pdobb Avatar answered Sep 30 '22 14:09

pdobb