Skip to content

Instantly share code, notes, and snippets.

@rosenfeld
Created July 18, 2014 11:47
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rosenfeld/dddd0f285fa024fe76fc to your computer and use it in GitHub Desktop.
Supporting automatic return from render/redirect/head in Rails
# Please don't comment in this gist since I'm not notified by any comments here:
# https://github.com/isaacs/github/issues/21
# This is the discussion to comment on: http://blog.arkency.com/2014/07/4-ways-to-early-return-from-a-rails-controller/
class ApplicationController < ActionController::Base
# ...
around_action :catch_halt
def render(*args)
super
throw :halt
end
def redirect(*args)
super
throw :halt
end
def head(*args)
super
throw :halt
end
private
def catch_halt
catch :halt do
yield
end
end
end
class SampleController < ApplicationController
def my_action
render body: 'response'
render body: "double rendering won't happen as this will never be executed"
end
end
@inspire22
Copy link

Using it! Man, I wish this was core, it's so much more elegant than other solutions.

@rosenfeld
Copy link
Author

I agree it's more elegant and I'd prefer it in the core too, but I'm afraid this could break third-party code that expect render/redirect/head not to return...

@spalenza
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment