LoginSignup
7
4

More than 5 years have passed since last update.

Engine側からどういうわけかmain_appのURL helperを使いたい

Posted at

例えばEngine側のコントローラーを以下のようにApplicationControllerを親として定義しているとする。

class Nyauth::Base < ApplicationController
end

ApplicationControllerを継承する理由は

  • layoutはマウント元アプリ側のものを使いたい
  • ApplicationControllerにある共通処理をEngine側のControllerでも使いたい

と言ったあたり。

この時地味に困るケースが有る。

  • before_actionなどで、マウント元アプリ側のurl helperを、main_app.とか付けずに普通に使いたいケース
  • layouts/application内にマウント元アプリ側のurl helperを、main_app.とか付けずに普通に使いたいケース

こんな時は、以下みたいなhelperを用意しておいて

module Nyauth
  module ApplicationHelper
    # engine側からmain_app側のurl helperを呼ぶ事ができるようにしておく
    # ApplicationControllerに記載されているbefore_actionで参照するケースや
    # layoutに記載されているlinkから参照されるケースがありうる
    def method_missing method, *args, &block
      if method.in? Rails.application.routes.url_helpers.instance_methods
        main_app.send(method, *args)
      else
        super
      end
    end
  end
end

マウント元アプリ側で

class ApplicationController < ActionController::Base
  include Nyauth:: ApplicationHelper
  helper Nyauth:: ApplicationHelper
end

みたいな感じで使うと、いいかも。

代替案

main_app.を全部のURL helperにつける

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4