开发者

How do I get my Rails 3.1 app to accept routes with an '@' symbol in the URL?

开发者 https://www.devze.com 2023-04-04 06:54 出处:网络
I have already setup the route file to include the username, via the Vanity gem. However, now I can do just one specific URL - i.e. their username.

I have already setup the route file to include the username, via the Vanity gem.

However, now I can do just one specific URL - i.e. their username.

So the route generated by the gem looks like this:

  controller :vanities do 
    match ':vname' => :show, :via => :get, :constraints => {:vname => /[A-Za-z0-9\-\+]+/}
  end

So say someone registers with the username test, the system will automagically create their vname based on their username. But what happens if they go to mydomain.com/@test, I want them to end up at the same route as if they just went to /test.

How do I do th开发者_JAVA技巧at?


You can allow an optional @ at the beginning of your vanity name with:

controller :vanities do 
  match ':vname' => :show, :via => :get, :constraints => {:vname => /@?[A-Za-z0-9\-\+]+/}
end

You would then have to strip the @ in your controller action, like this:

params[:vname].gsub!(/\A@/, '')

Update

If you want the replacement done in all your controllers, you can do it in a before_filter in your ApplicationController:

class ApplicationController < ActionController::Base
  before_filter :rename_vanity

  def rename_vanity
    params[:vname].gsub!(/\A@/, '') if params[:vname]
  end
end


The @ symbol is a reserved character in URLs, and must be percent-encoded (as %40) when used outside the particular context @ is reserved for. The URL mydomain/@test simply isn't valid.

0

精彩评论

暂无评论...
验证码 换一张
取 消