问题
I'm trying to use the method outlined this post in conjunction with url_for
to determine if the current path is in a mounted engine, but I'm having a hard time figuring out how exactly to use Journey::Path::Pattern
(which is what is returned by the mounted_path
method outlined in the other post).
class Rails::Engine
def self.mounted_path
route = Rails.application.routes.routes.detect do |route|
route.app == self
end
route && route.path
end
end
There doesn't seem to be too much discussion on it anywhere, aside from the official documentation, which wasn't particularly helpful. I'm sure the solution is relatively simple, and the gist of the helper method I'm trying to write is below:
def in_engine? engine
current_url.include?(engine.mounted_path)
end
Edit:
Some of my engines are mounted as subdomains and some are mounted within the app itself, preventing me from simply checking if the current subdomain is the same as the mounted path, or using path_for
.
回答1:
Not exactly a solution, but maybe a useful lead.
I found your question interesting, so I started delving deep inside rails source... what a scary, yet instructive trip :D
Turns out that Rails' router has a recognize
method that accepts a request
as argument, and yields the routes that match the request.
As the routes have an app
method you can compare to your engine, and as you can have access to the request
object (which takes into account the http method, subdomain, etc), if you find out how to have direct access to the router instance, you should be able to do something along the lines of :
def in_engine?(engine)
router.recognize(request) do |route,*|
return true if route.app == engine
end
false
end
EDIT
I think i found out, but it's late here in I have no rails app at hand to test this :(
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
EDIT
also, maybe a simpler workaround would be to do this :
in your main app
class ApplicationController < ActionController::Base
def in_engine?(engine)
false
end
helper_method :in_engine?
end
then in your engine's application controller
def in_engine?(engine)
engine == ::MyEngine
end
helper_method :in_engine?
来源:https://stackoverflow.com/questions/19456321/determine-if-journeypathpattern-matches-current-page