Path Expander
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/projectsNow 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 /projectsThis will work of course, but it isn’t all that elegant. Another option would be something along the lines of:
projects_path(:user_id => current_user.id)This solution will also work and has the benefit of being concise. Unfortunately we lose the nice route formatting. Instead of “/users/:id/projects”, we get “/projects?user_id=:id”. Not the prettiest result.
So I started thinking, wouldn’t it be great if Rails would automatically expand that path into “/users/:id/projects” if possible and if not just fall back to “/projects”. I started hacking around a bit and this is what I came up with:
The biggest downside to this is the call to #recognize_path. From my understanding, this can be a bit computationally intensive, so if you’re worried about top notch performance, this solution may be a bit risky.
So have you dealt with this before? If so, have you been able to come up with a better solution than this?