1

すべてのデバイスコントローラーを含む一部のコントローラーに適用される before_helpers と helper_methods のセットがあります。

フィルターの前にそれらを宣言する好ましい方法は何でしょうか?

この記事を試してみましたが、成功しませんでした (エラーが発生しましたsessions_controller.rb to define Devise::SessionsController (LoadError))。そして、すべてのコントローラーをやり直した場合、同じコードを宝石から再度コピーする必要がありますが、これは反復的に見えます。

どうすればこれを行うことができますか?

4

1 に答える 1

1

を配置して、Devise コントローラーの名前かどうかを確認before_filterします。application_controller.rbparams[:controller]

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
    before_filter :check_if_devise

    private

    def check_if_devise
        if ['confirmations', 'omniauth_callbacks', 'passwords', 'registrations', 'sessions', 'unlocks'].include? params[:controller]
            # logic for before_filter
        end
    end
end

アップデート:

before_filterまたは、既存のロジックとは別に維持したい場合check_if_deviseは、既存の関数を削除してbefore_filter、条件付きロジックがcheck_if_deviseパスした場合にのみ呼び出すことができます。

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
    before_filter :check_if_devise

    private

    def check_if_devise
        if ['confirmations', 'omniauth_callbacks', 'passwords', 'registrations', 'sessions', 'unlocks'].include? params[:controller]
            function_to_run
        end
    end

    def function_to_run
        # code goes here
    end
end

これを配置すると、Devise コントローラーに対してapplication_controller.rbが確実に実行されます。その他の個別の 1 回限りのコントローラーについては、次のようにbefore_filter呼び出すことができます。function_to_runbefore_filter

# app/controller/random_controller.rb
class RandomController < ApplicationController
    before_filter :function_to_run

end
于 2013-07-11T20:24:03.903 に答える