【问题标题】:Inspect a given route to determine if it has a subdomain constraint检查给定路由以确定它是否具有子域约束
【发布时间】:2017-11-15 22:20:06
【问题描述】:

我正在构建一个具有 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_urlabout_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

这可能吗?

【问题讨论】:

    标签: ruby-on-rails routes rails-routing url-helper


    【解决方案1】:

    我可以检查给定路由以查看它是否具有子域约束吗?

    是的,这是可能的。您需要使用 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
    

    上面通过它的名字搜索一个路由,如果找到了它就检查它的约束。

    【讨论】:

    • 这太完美了!非常感谢 :) 如果您有时间,我遇到了一个问题,opts 可以是 AR 模型而不是哈希。例如,user_url(@user) (smart_url('user', @user))。我不能将 subdomain 参数附加到此。有什么想法吗?
    • @JodyHeavener -- 请查看我更新的答案。对于这种情况,您可以手动进行类型检查。
    【解决方案2】:

    你可以像这样在 lib 文件夹下创建类

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 2012-09-07
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多