Quick tip - Flexible filters with respond_to
September 02 2006
Are you using filters in your controllers to pre-load objects and DRY up your actions? Take for example a RESTful customer controller. We know we want to load the customer record for the show, edit, update, and destroy actions and views.
class CustomersController < SecureController
before_filter :find_customer, :except => [ :index, :new, :create ]
...
private
def find_customer
@customer = Customer.find_by_id(params[:id])
end
end
This works but is brittle. What happens when the filter can’t locate the customer? Should we display a flash message? What happens if this is an Ajax request? What if the call is through an API?
That’s where the following method can help…
def halt_and_respond_with(message)
respond_to do |type|
type.html do
flash[:error] = message
render :template => 'shared/message'
end
type.js do
render :update do |page|
page.alert(message)
end
end
type.xml { render :text => message }
end
false
end
Add this puppy to your application.rb and then refactor your filters like this:
class CustomersController < SecureController
before_filter :find_customer, :except => [ :index, :new, :create ]
...
private
def find_customer
@customer = Customer.find_by_id(params[:id])
return halt_and_respond_with('Invalid customer.') if @customer.nil?
end
end
Comment or question via @depixelate

FYI: This post was migrated over from another blogging engine. If you encounter any issues please let me know on @depixelate. Thanks.