Path Expander

Posted by Peter Wagenet Sat, 07 Mar 2009 21:05:00 GMT

UPDATE: This is not necessary. See this post for details.

From time to time, I’ve been working on a Rails app with nested routes and ran into the situation where I want to nest the url only if I have the necessary information. Consider the following example to see what I mean:

user_projects_path(current_user) #=> /users/:id/projects

Now this will work perfectly if current_user is defined, but what if current_user is nil? Unfortunately, I’ll end up with the less than desirable “/users//projects”. To avoid this I could use an if statement along the lines of:

current_user ? user_projects_path(current_user) : projects_path
#=> /users/:id/projects or /projects

This will work of course, but it isn’t all that elegant. Another option would be something along the lines of: