我正致力于干燥API。一切都进展顺利,但我注意到每个班级的二十行左右几乎是一样的:
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
我想干这些,但问题是我需要在当前类I(而不是超类)的上下文中运行这些回调。对于before_filters
,我知道您通常可以将这些内容移至V1::BaseController
,但就我而言,这会导致执行顺序出现问题,因为before_filters
中有其他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
我尝试将self
传递给super_init
并将所有逻辑放在class << passed_context
内,但这并不起作用。我可以列出我尝试过的东西,但我不确定对任何人有多大帮助...
如果您需要更多信息,请询问。我觉得这是一个更高级别的抽象,我以前不必在Rails中做过。
谢谢!
答案 0 :(得分:0)
你试过prepend_before_action吗?这使您可以更好地控制执行顺序。
另一方面,由于before_action
语法will be deprecated soon
before_filter
代替before_action
会很棒