我正在尝试基于此 railscast为 Rails 制作域通配符路由。但我想在本机路由中制作与“范围”功能一样好的功能,例如
domain ':city_id.mysite.com' do
root :to => "cities#test"
end
恕我直言,它看起来比正则表达式更漂亮,但是我懒得自己为“:city_id.mysite.com”之类的路径编写解析器。我相信它已经存在于rails内部的某个地方,但我在源代码中找不到它。为这条路线使用 :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”