Is it possible to add validation to the user model so that user names that match already defined routes are rejected?
For instance:
get 'search'
get :username => "users#show", :as => :user
If the user enters “search” as the username, he will reject it because it already exists as a rail route.
A possible other approach is to create an explicit blacklist, but obviously this requires more maintenance when adding new routes.
Edit
Adapted answer in working solution:
validate :username_blacklist
private
@@username_blacklist = nil
def username_blacklist
unless @@username_blacklist
@@username_blacklist = Set.new [ "badword", "naughtybadfun"]
Rails.application.routes.routes.each do |r|
reserved_word = File.dirname(r.path).split('/')[1]
@@username_blacklist << reserved_word if reserved_word
end
end
errors.add(:username, "is restricted") if @@username_blacklist.include?(username)
end
Paul source
share