Reputation: 369
I'm trying to make a domain wildcard routing for Rails based on this railscast. But I'd like to make as nice as "scope" function in native routing, e.g.
domain ':city_id.mysite.com' do
root :to => "cities#test"
end
IMHO it looks like more prettier than regexps, but I'm too lazy to write the parser for the path like ":city_id.mysite.com" by my own. I belive somewhere inside rails it already exists, but I can't find it in source code. Also would be great to use :constraints, :as, :scope and other configs for this route, but htis is optionally.
For now my code looks like:
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)
So, I'm able to create routes only for the subdomains
domain 'subdomain' do
root :to => "cities#test"
end
And I can get only hardcoded parameter 'city_id' in controller
Upvotes: 1
Views: 440
Reputation: 369
Ok, maybe will be usefull for someone. I've found, that Journey::Path::Pattern can be used for this. Adding to intializer:
@pattern = Journey::Path::Pattern.new(
Journey::Router::Strexp.compile(path, constraints, ['.'])
)
And when checking -
match_data = @pattern.match(request.host)
return false if match_data.nil?
Upvotes: 0