检查给定路由以确定它是否具有子域约束
Inspect a given route to determine if it has a subdomain constraint
我正在构建一个具有 merchant
子域的 Rails 应用程序。我有这两条路线:
get '/about', controller: :marketing, action: :about, as: :about
get '/about', controller: :merchant, action: :about, constraints: { subdomain: 'merchant' }, as: :merchant_about
但是当我使用他们的 URL 助手时 merchant_about_url
和 about_url
都会导致 http://example.com/about
.
我知道我可以在帮助程序上指定 subdomain
参数来为 URL 添加子域前缀,但是由于这些 URL 将在各种情况下频繁使用我想为这个助手构建一个包装器,使其更智能。
我的问题:我可以检查给定路由以查看它是否具有子域约束吗?
如果可以,我想做如下事情:
def smart_url(route_name, opts={})
if # route_name has subdomain constraint
opts.merge!({ subdomain: 'merchant' })
end
send("#{route_name}_url", opts)
end
这样做,我可以有效地调用:
smart_url('about') # http://example.com/about
smart_url('merchant_about') # http://merchant.example.com/about
这可能吗?
您可以像这样在 lib 文件夹下创建 class
class Subdomain
def self.matches?(request)
case request.subdomain
when SUB_DOMAIN_NAME
true
else
false
end
end
end
并在您的 routes.rb 文件中创建这样的路线
constraints(Subdomain) do
get '/about', to: 'marketings#about', as: :about
end
get '/about', to: 'marketings#about', as: :merchant_about
Can I inspect a given route to see if it has a subdomain constraint?
是的,这是可能的。您需要使用 Rails' routes API 来获取有关路线的信息。
def smart_url(route_name, opts={})
route = Rails.application.routes.routes.detect {|r| r.name == route_name }
if opts.is_a? Hash && route&.constraints[:subdomain]
opts.merge!({ subdomain: 'merchant' })
end
send("#{route_name}_url", opts)
end
以上通过名称搜索路由,如果找到路由则检查其约束。
我正在构建一个具有 merchant
子域的 Rails 应用程序。我有这两条路线:
get '/about', controller: :marketing, action: :about, as: :about
get '/about', controller: :merchant, action: :about, constraints: { subdomain: 'merchant' }, as: :merchant_about
但是当我使用他们的 URL 助手时 merchant_about_url
和 about_url
都会导致 http://example.com/about
.
我知道我可以在帮助程序上指定 subdomain
参数来为 URL 添加子域前缀,但是由于这些 URL 将在各种情况下频繁使用我想为这个助手构建一个包装器,使其更智能。
我的问题:我可以检查给定路由以查看它是否具有子域约束吗?
如果可以,我想做如下事情:
def smart_url(route_name, opts={})
if # route_name has subdomain constraint
opts.merge!({ subdomain: 'merchant' })
end
send("#{route_name}_url", opts)
end
这样做,我可以有效地调用:
smart_url('about') # http://example.com/about
smart_url('merchant_about') # http://merchant.example.com/about
这可能吗?
您可以像这样在 lib 文件夹下创建 class
class Subdomain
def self.matches?(request)
case request.subdomain
when SUB_DOMAIN_NAME
true
else
false
end
end
end
并在您的 routes.rb 文件中创建这样的路线
constraints(Subdomain) do
get '/about', to: 'marketings#about', as: :about
end
get '/about', to: 'marketings#about', as: :merchant_about
Can I inspect a given route to see if it has a subdomain constraint?
是的,这是可能的。您需要使用 Rails' routes API 来获取有关路线的信息。
def smart_url(route_name, opts={})
route = Rails.application.routes.routes.detect {|r| r.name == route_name }
if opts.is_a? Hash && route&.constraints[:subdomain]
opts.merge!({ subdomain: 'merchant' })
end
send("#{route_name}_url", opts)
end
以上通过名称搜索路由,如果找到路由则检查其约束。