What path is a mountable engine mounted on

后端 未结 4 1357
故里飘歌
故里飘歌 2021-02-04 14:50

I need to know, from inside of a layout of a mountable engine, what path it\'s currently being mounted on. What would be the way to do it?

E.g. my routes.rb contains the

4条回答
  •  情话喂你
    2021-02-04 15:53

    If the engine is mouted :as => a different name, querying named_routes will not be sufficient. This monkey patch will do:

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

    Now call mounted_path on the engine:

    BackendCore::Engine.mounted_path => "/backend"
    

    Note: be careful, in production mode, the classes in your engine are evaluated before the routes of the main app are loaded. Calling this method in class macros might not work!

提交回复
热议问题