Tuesday, September 15, 2009

Action prerequisites in Rails

Have you ever had a series of pages (controller actions/views) that must be seen in order, because each page sets up prerequisite information for the next? Perhaps like a wizard, a series of pages with forms on them that bring you eventually to a page that does something with that data.

I've come up with a really simple and elegant solution for managing prerequisites in Rails. Since it doesn't take much code, it's easier to just plop it in your project instead of as a plugin (at least in my opinion)...


Here's how it works: Using an around_filter, I can provide a way to jump out of the action when checking the prerequisites. To specify (and check) a prerequisite, simply give it a name: "prerequisite :login". To check the prerequisite, it will call the "login?" method. If that returns true, everything's fine and we'll continue on our merry way into the action, or to the next prerequisite (if you have several). If false, it throws a :prerequisite_unmet, which means it exits the current method and continues on in our catcher method. Next order of business is simply to redirect to the :login action.

0 comments: