以下是我对控制器的关注Concerns::V1::PlanFinding
。根据{{1}}控制器和操作,它会调用base
set_plan
下面是一个控制器,我将其引起关注:
extend ActiveSupport::Concern
attr_accessor :plan, :custom_key
included do |base|
actions = case base.to_s
when "Api::V1::PlansController"
[:show, :total_prices, :update]
when "Dist::PlansController"
[:show, :total_prices, :flight_info]
end
if actions.present?
before_action :set_plan, only: actions
else
before_action :set_plan
end
end
def set_plan
@plan = Model.find('xxx')
@custom_key = params[:custom_key] || SecureRandom.hex(10)
end
这很好。但是关注代码过多地与class Dist::PlansController
include ::Concerns::V1::PlanFinding
控制器混在一起。
我的问题是:由于我们无法在控制器中使用如下所示的base
选项。如何实现我自己的only
选项以包含或找到一种新方法将only
控制器与关注点分离:
base
答案 0 :(得分:1)
AFAIK开箱即用是不可能的。我使用以下方法:
included do |base|
actions = base.const_defined?('PLAN_FINDING_USE') &&
base.const_get('PLAN_FINDING_USE')
if actions.is_a?(Array)
before_action :set_plan, only: actions
else
before_action :set_plan
end
end
和
class AdministratorCreateUpdateSerializer(ModelSerializer):
username = serializers.CharField(
source='user.username',
validators=[UniqueValidator(queryset=User.objects.all())]
)
email = serializers.EmailField(
source='user.email',
validators=[UniqueValidator(queryset=User.objects.all())]
)
password = serializers.CharField(
source='user.password',
allow_blank=True,
style={'input_type': 'password'}
)
first_name = serializers.CharField(
source='user.first_name'
)
last_name = serializers.CharField(
source='user.last_name'
)
class Meta:
model = Administrator
fields = [
'username',
'email',
'password',
'first_name',
'last_name',
]