Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you make sure a username won't conflict with an existing route?

So I'd like to have urls on my site like http://foobar.com/hadees that goes to someone's profile. However when registering usernames how do I make sure they don't pick something that will conflict with my existing routes?

I'm guessing I need to get a list of the existing routes but I'm not sure how to do it.

like image 275
hadees Avatar asked Mar 28 '12 17:03

hadees


2 Answers

A short google search gives me that:

http://henrik.nyh.se/2008/10/validating-slugs-against-existing-routes-in-rails

In rails 3 the method has moved to Rails.application.routes.recognize_path

So I summarize :

class User < ActiveRecord::Base
  validates_format_of :name, :with => /\A[\w-]+\Z/
  validates_uniqueness_of :name
  validate :name_is_not_a_route

protected

  def name_is_not_a_route
    path = Rails.application.routes.recognize_path("/#{name}", :method => :get) rescue nil
    errors.add(:name, "conflicts with existing path (/#{name})") if path && !path[:username]
  end

end
like image 87
Thomas Guillory Avatar answered Sep 28 '22 01:09

Thomas Guillory


Good question. Through a little tinkering, I found that you can get the routes in your app via:

Rails.application.routes.routes.collect{|r| r.path}
like image 20
miked Avatar answered Sep 28 '22 03:09

miked