2012-04-04 95 views
2

我有这个在我的routes.rb文件:在routes.rb中访问当前请求?

class SubdomainWww 
    def self.matches?(request) 
    request.subdomain.start_with? "www." 
    end 

    def self.strip_www(subdomain) 
    if subdomain.start_with? "www." 
     subdomain.slice!(4..-1) 
    else 
     subdomain 
    end 
    end 
end 

MyApp::Application.routes.draw do 

    constraints(SubdomainWww) do 
    match '*path', :to => redirect(:subdomain => SubdomainWww.strip_www(???)) 
    match '/', :to => redirect(:subdomain => SubdomainWww.strip_www(???)) 
    end 
... 

,如果这是去除WWW目的。对于子域名(例如,www.sub.domain.tld应该重定向到sub.domain.tld;子域名稍后用于标识客户端)。 如何更换'???'以便当前请求的子域(字符串)被传递给函数strip_www()?

在此先感谢!

+0

我相信这是一个更好的解决方案在更基础的水平。您可以在DNS设置中设置一个标志,禁止www子域名。 – Ekampp 2012-04-04 22:11:28

+0

是的,那可能是对的。 但它仍然有可能以这种方式解决它。该方法匹配?也可以访问请求的子域.... – Daniel 2012-04-05 13:12:55

+0

可能可以做这项工作。我不知道如何,我不确定这是解决问题的最佳方式。所以我会把建议的解决方案留给其他人。祝你好运。 – Ekampp 2012-04-08 13:14:06

回答

0

不知道这会起作用还是有帮助,但是我在使用具有Devise的Cells时遇到了同样的问题,其中Devise current_ *方法想要将env和warden存储在请求中。我有一个路由到一个单元格(控制器和视图),为我渲染了单元格的视图。我将请求加入Cell的控制器的方式是通过route.rb作为请求传入自己。

match "/dashboard/widget/:name" => proc { |env| 
    cell_name = env["action_dispatch.request.path_parameters"][:name] 
    [ 200, {}, [ Cell::Base.render_cell_for(cell_name, :display, :request => self) ]] 
} 

注意:request => self。当你在路由中时,self就是ActionDispatch :: Request对象本身。只要传递请求,你应该很好。

MyApp::Application.routes.draw do 

    constraints(SubdomainWww) do 
    match '*path', :to => redirect(:subdomain => SubdomainWww.strip_www(self)) 
    match '/', :to => redirect(:subdomain => SubdomainWww.strip_www(self)) 
    end 
...