gpt4 book ai didi

ruby-on-rails - 确定 Journey::Path::Pattern 是否匹配当前页面

转载 作者:数据小太阳 更新时间:2023-10-29 07:19:51 25 4
gpt4 key购买 nike

我正在尝试使用概述的方法 this post结合 url_for 来确定当前路径是否在已安装的引擎中,但我很难弄清楚如何使用 Journey::Path::Pattern(这是另一篇文章中概述的 mounted_pa​​th 方法返回的内容)。

class Rails::Engine
def self.mounted_path
route = Rails.application.routes.routes.detect do |route|
route.app == self
end
route && route.path
end
end

除了the official documentation,似乎没有太多关于它的讨论。 ,这不是特别有用。我确定解决方案相对简单,我尝试编写的辅助方法的要点如下:

def in_engine? engine
current_url.include?(engine.mounted_path)
end

编辑:

我的一些引擎作为子域安装,一些引擎安装在应用程序本身内,阻止我简单地检查当前子域是否与安装路径相同,或使用 path_for

最佳答案

不完全是解决方案,但可能是一个有用的线索。

我发现你的问题很有趣,所以我开始深入研究 rails 源代码......多么可怕,但很有启发性的旅行:D

事实证明,Rails 的路由器有一个recognize method它接受一个 request 作为参数,并产生与请求匹配的路由。

由于路由有一个 app 方法,您可以将其与您的引擎进行比较,并且您可以访问 request 对象(考虑到 http 方法,子域等),如果你知道如何直接访问路由器实例,你应该能够按照以下方式做一些事情:

  def in_engine?(engine)
router.recognize(request) do |route,*|
return true if route.app == engine
end
false
end

编辑

我想我发现了,但这里已经晚了,因为我手头没有 Rails 应用程序来测试它:(

  def in_engine?(engine)
# get all engine routes.
# (maybe possible to do this directly with the engine, dunno)
engine_routes = Rails.application.routes.set.select do |route|
route.app == engine
end
!!engine_routes.detect{ |route| route.matches?(request) }
end

编辑

另外,也许更简单的解决方法是:

在您的主应用中

  class ApplicationController < ActionController::Base
def in_engine?(engine)
false
end
helper_method :in_engine?
end

然后在引擎的应用程序 Controller 中

  def in_engine?(engine)
engine == ::MyEngine
end
helper_method :in_engine?

关于ruby-on-rails - 确定 Journey::Path::Pattern 是否匹配当前页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19456321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com