Keep track of reserved URLs (to enable vanity per-user URLs)
On my rap lyrics explanation website, every user has an associated "favorites" page at http://r开发者_开发技巧apgenius.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?
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
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
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...
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?
精彩评论