views:

96

answers:

4

On my rap lyrics explanation website, every user has an associated "favorites" page at http://rapgenius.com/USERNAME

Because these favorites pages occupy the root namespace, I have to make sure that no one takes a username that I'm already using for something else. E.g.:

  • /songs
  • /lyrics
  • /users
  • /posts

How can I look up all top-level paths that have higher precedence than the /username route (which is at the bottom of routes.rb) at the time of user creation so I can prevent users from taking these reserved names?

A: 

Maybe you could make use of this?

But it looks like it raises on no match, so you might have to write a wrapper for it to rescue false on those cases.

I also just realized you would have to also inspect any match to make sure it's not the user route you will want it to match...

floyd
+2  A: 

Why not make things easier for yourself and simply do:

def validate
  reserved = %w(songs lyrics users posts)
  errors.add(:username, 'is not allowed') if reserved.include?(username)
end
John Topley
So resign myself to manually updating this list when I add a new resource? Might be the least overall hassle here, I suppose
Horace Loeb
I don't know your application, but realistically how often are you going to be adding new routes? Besides, the code above reveals its intent very clearly and is decoupled from the view. Finally, the Rails 3 router is a different animal, so any clever code you use to introspect the routes now is ripe for future breakage.
John Topley
A: 

Two counter-questions:

1) Why does the "favorites" page for each user need to live in the root of your URI tree?

2) How do you currently deal with the situation where two users choose the same username?

Peter
A: 

If you want to pull in a plugin to do this a useful one is friendlyid

From their site

FriendlyId is the “Swiss Army bulldozer” of slugging and permalink plugins for Ruby on Rails. It allows you to create pretty URLs and work with human-friendly strings as if they were numeric ids for ActiveRecord models.

More importantly for you it has support for making sure the urls generated don't match you controllers/paths

markdevilliers