Model validation to reject specific routes from username

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

# checks if the username is on a blacklist
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
+3
source share
3 answers

In your check, you can go through all the specific routes and check them for the desired username.

This will help you get specific paths:

Rails.application.routes.routes.each {|r| p r.path.to_s}
+1

- URL-, 404 PageNotFound, :)

+1

Well, you already got the desired behavior, because the first mapped route is used. Thus, the query / search will never reach the second route.

0
source

All Articles