这是DRY的好方法吗?

| 我的控制器动作如下:
# check if user is already working
if current_user.working?
  flash[:error] = I18n.translate \'error.working\'    
  redirect_to labor_url and return          
end

# check if user is doing a quest
if current_user.has_tavern_quest?
  flash[:error] = I18n.translate \'error.has_quest\'      
  redirect_to labor_url and return          
end
现在,这是一些似乎在其他控制器及其动作中重复的代码。因此,我认为稍微干燥一下是个好主意。我想到创建一个类似的用户方法:
def is?(states)
    possible_states = :working, :doing_tavern_quest
    # check states
    # set flash messages, do the same things as above without the redirects
end
我的想法是,我现在将在动作中使用类似的内容:
redirect_to labor_url if current_user.is?(:working, :doing_tavern_quest)
您认为这是个好主意吗?是干掉事情的好方法还是我可以做得更好?     
已邀请:
我喜欢和返回模式。 但是,除非存在许多不同的动态条件,否则为什么不将用户状态尽可能地封装在模型中? 除非控制器需要了解详细信息,否则如何:
redirect_to labor_url if current_user.busy? # no parameters
顺便说一句,控制器方法不返回任何内容,您可以这样做:
return redirect_to labor_url if current_user.busy?
    
current_user.is?(state)原则上没有什么问题,除了名称(is_one_of?...)
def is?(states)
    possible_states = [:working, :doing_tavern_quest] # note square brackets here
    # check states
    # set flash messages, do the same things as above without the redirects
end
您可以提取重定向行的方法,并在ApplicationController类中创建一个方法,以使代码更加干燥(如果重定向到同一位置)。     

要回复问题请先登录注册