New rails plugin: validate_request
July 26th, 2006One thing that bothered me when I started using rails was that there wasn’t a built-in way to verify that your actions are getting the correct arguments. For example, in this typical action:
def show
@dog = Dog.find(params[:id])
end
an exception is raised if the “id” parameter is omitted (e.g. /dog/show rather than /dog/show/5), and you get a rails application error by default. It seemed like there should be a way to declare that this action requires an “id” parameter of type integer, and provide a graceful way to recover if that constraint isn’t met.
This was something that we had built into our in-house PHP framework long ago, and we had become quite accustomed to it. Such a feature essentially allows you to describe and enforce the interface to your controllers’ actions.
It’s a good exercise to define the set of valid methods and parameters that can be used to call your actions, and it’s very handy to have notification and helpful logging messages for when your constraints aren’t met. It’s the same argument as the one that says that you should carefully consider the interface between your classes.
So I wrote a new plugin called validate_request to easily perform this type of checking, and recover gracefully (and configurably) if the constraints aren’t met. Now you can specify constraints like this:
def show
validate_request(:get, :id => :integer) or return
@dog = Dog.find(params[:id])
end
and perhaps more importantly like this:
def update
validate_request(:post, :id => :integer, :dog => Dog) or return
@dog = Dog.find(params[:id])
@dog.update_attributes(params[:dog])
...
end
This way, your argument checking isn’t as tightly coupled to your database schema — attributes can be added and removed from the Dog model, and you won’t have to change your request validation code.
That’s a lot of benefit for only one line of code per action.
You can install the plugin by running the following commands from your rails application’s directory:
./script/plugin source svn://rubyforge.org//var/svn/validaterequest/plugins
./script/plugin install validate_request
Here are some other resources:
- The RubyForge project page
- The README file
- The USAGE file, which gives more in-depth instructions on how to use validate_request in your code
There are a few items that are on the to-do list, such as support for aspects in RESTful URLs, and what amounts to enumerated types.
Let me know how things work out for you.
