2013-02-24 117 views
1

我正在尝试为基于this railscast的Rails进行域通配符路由。但是我希望在本地路由中像“范围”功能一样好,例如Rails路由域通配符

domain ':city_id.mysite.com' do 
    root :to => "cities#test" 
    end 

恕我直言,看起来比正则表达式更漂亮,但我懒得写解析器像路径:由我自己“city_id.mysite.com”。我相信它已经存在的轨道内的某个地方,但我无法在源代码中找到它。 对于这条路线,使用:constraints,:as,:scope和其他配置也是很好的选择,但htis是可选的。

现在我的代码如下所示:

module Domain 
    class Match 
    def initialize(wildcard, *options) 
     @wildcard = wildcard 
    end 

    def matches?(request) 
     request.path_parameters[:city_id] = request.subdomain #to replace this with setting parameters from wildcard, :default and so on 
     request.subdomain.present? #to replace this string with wildcard-match condition 
    end 
    end 

    module Mapper 
    def domain(wildcard='') 
     constraints(Domain::Match.new wildcard) { yield } 
    end 
    end 
end 

ActionDispatch::Routing::Mapper.send(:include, Domain::Mapper) 

所以,我只能够为子域

domain 'subdomain' do 
    root :to => "cities#test" 
    end 

,我可以得到唯一的硬编码参数创建路线“city_id”在控制器

回答

0

好的,也许会对某人有用。我发现,Journey :: Path :: Pattern可以用于这个。添加到初始化器:

@pattern = Journey::Path::Pattern.new(
     Journey::Router::Strexp.compile(path, constraints, ['.']) 
) 

而且检查时 -

match_data = @pattern.match(request.host) 
    return false if match_data.nil?