2013-02-24 120 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?