What path is a mountable engine mounted on

后端 未结 4 1351
故里飘歌
故里飘歌 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:29

    Evaluating the routes to get the mount path can give unexpected results when engines are mounted inside other engines.

    When you take a look at https://github.com/rails/rails/pull/5008 you can read the comment by Jose Valim:

    Also, an engine can be mounted inside another engine, so it is unlikely that this will give you the proper result. The best option is probably to have a configuration option where the developer will set the path.

    For consistent results, I'm now using an accessor on the engine.

    For example:

    # APP/initializers/backend_core_engine.rb
    BackendCore::Engine.mount_path = "/backend"
    
    # APP/config/routes.rb
    mount BackendCore::Engine => BackendCore::Engine.mount_path
    
    # ENGINE/backend_core/lib/engine.rb
    module BackendCore
      class Engine < ::Rails::Engine
        cattr_accessor :mount_path
      end
    end
    

提交回复
热议问题