私は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_init
へself
に渡すとclass << passed_context
内のすべてのロジックを入れてみましたが、それは動作しませんでした。私は試したもののリストを与えることができましたが、誰にでも役立つかどうかは分かりません...
これ以上の情報が必要な場合はお尋ねください。私は以前これをRailsでやっていなくてもいいという、より高いレベルの抽象概念であると感じています。
ありがとうございます!
以来
before_action
の代わりbefore_filter
を使うのは素晴らしいことと思います。 –これで、 'prepend_before_filter'を使うことができます。 – rebagliatte
@ party_hat_24はこれをあなたのために活用しましたか? – rebagliatte