Created
March 25, 2012 19:16
-
-
Save warmwaffles/2199142 to your computer and use it in GitHub Desktop.
Programming By Contract within a controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class WidgetsController < ApplicationController | |
# ... | |
# other functions | |
# | |
def create | |
widget = Widget.new(params[:widget]) | |
widget.foo = some_thing | |
widget.bar = some_other_thing | |
widget.save! | |
# It was successful | |
respond_to do |format| | |
format.html { redirect_to widgets_path, :notice => "Huzzah it works" } | |
end | |
rescue | |
# Do your error handling here | |
respond_to do |format| | |
format.html { render :action => :new, :error => "You are an idiot" } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a way for you to keep your error handling code separate from your main logic flow. It makes this super handy in rather complicated controllers. Granted you should be doing skinny controller and fat models, but there are cases where the controller will need to be a bit chubby
Now if you wanted to, you could just do
but sometimes I need to set attributes that aren't
attr_accessible
For more information on Exception handling, take a look at this:
http://blip.tv/avdi-grimm/exceptional-ruby-4778405