2016-11-08 6 views
0

私はAPIをDRYしています。すべてがうまくいってきたが、私は、各クラスの20行ほどがほぼ同じであることに気付きました:Railsコールバックを修復する

class V1::FooController < V1::BaseController 
    # documentation 
    swagger_controller :Foo, "Foo" 
    # authorization 
    before_filter  :allow_session_user 
    before_filter  :allow_api_key_user, only: [:sample, :index] 
    before_filter  :check_access 
    # inherit crud endpoints 
    inherit_resources 
    actions :all, :except => [ :index, :show ] 
    # other 
    before_filter  :private_foo_method 
    respond_to   :json 

    #...other stuff...# 
end 

私はこれらを枯渇したいのですが、問題は、私は、これらのコールバックを実行する必要があります現在のクラスのコンテキストです(スーパークラスではありません)。 before_filtersについては、普通はV1::BaseControllerまで移動することができますが、私の場合は、がV1::BaseControllerにあるため、実行順序に問題が発生します。

class V1::BaseController < ApplicationController 
    #this needs to execute in the context of the class that called it and NOT V1::BaseController 
    def super_init(documentation_name, allowed_api_endpoints, except_inherited_crud) 
     swagger_controller documentation_name, documentation_name 
     inherit_resources 
     # authorization 
     before_filter  :allow_session_user 
     before_filter  :allow_api_key_user, only: allowed_api_endpoints 
     before_filter  :check_access 
     # inherit crud endpoints 
     inherit_resources 
     actions :all, :except => except_inherited_crud 
     # other 
     respond_to   :json 
    end 

end 

class V1::FooController < V1::BaseController 
    before_filter :init 
    before_filter :private_foo_method 

    def init 
     # super_init should run in the context of V1::FooController 
     super.super_init("Foo", [:sample, :index], [ :index, :show ]) 
    end 

    #...other stuff...# 
end 

は私がsuper_initselfに渡すとclass << passed_context内のすべてのロジックを入れてみましたが、それは動作しませんでした。私は試したもののリストを与えることができましたが、誰にでも役立つかどうかは分かりません...

これ以上の情報が必要な場合はお尋ねください。私は以前これをRailsでやっていなくてもいいという、より高いレベルの抽象概念であると感じています。

ありがとうございます!

答えて

0

prepend_before_actionを試しましたか?これにより、実行の順序を少しずつ制御することができます。サイドノートでは

、私たちが私たちは、フィルタを使用してきたのRailsの古いバージョンにしているbefore_action構文will be deprecated soon

+0

以来before_actionの代わりbefore_filterを使うのは素晴らしいことと思います。 –

+0

これで、 'prepend_before_filter'を使うことができます。 – rebagliatte

+0

@ party_hat_24はこれをあなたのために活用しましたか? – rebagliatte

関連する問題