Skip to content

Instantly share code, notes, and snippets.

@warmwaffles
Created March 25, 2012 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save warmwaffles/2199142 to your computer and use it in GitHub Desktop.
Save warmwaffles/2199142 to your computer and use it in GitHub Desktop.
Programming By Contract within a controller
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
@warmwaffles
Copy link
Author

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

widget = Widget.create!(params[:widget])

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

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