简体   繁体   中英

Enforcing URL trailing slashes for mounted engines in Rails

I have an engine called Battalion mounted into my host application like so:

mount Battalion::Engine => '/@:site_username'

The Battalion engine is conceptually a different website than the host application; it has separate assets, etc. The problem I am encountering has to do with trailing slashes. When I visit the route http://localhost:3000/@jon I want to be redirected to the same route but with a trailing slash, like http://localhost:3000/@jon/ .

This is important because I want to use relative URLs for assets once the user is in the engine.

I am aware of the trailing_slash option that can be applied to link helpers, but I want to enforce the redirection at the controller level, and not for each link. I also read a blog post that offered a good solution, but it breaks in my particular case because I am using the :site_username variable within my route.

Turns out the best way to handle this is a slight modification of the answer found in this post . His advice isn't quite applicable in this case because there is a parameter embedded in the URL to the engine. Here's the solution I found:

In the application_controller.rb of the engine:

def ensure_trailing_slash
  redirect_to url_for(params = :trailing_slash => true), :status => 301 unless trailing_slash?
end

def trailing_slash?
  request.env['REQUEST_URI'].match(/[^\?]+/).to_s.last == '/'
end

In the controller that contains the root path:

before_filter :ensure_trailing_slash, :only => :index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM