更好的方法来重构/重写检查许多参数[:action]的凌乱方法?

时间:2013-05-29 09:58:18

标签: ruby-on-rails ruby-on-rails-3 refactoring location params

我的application_controller.rb里面有几个方法,因为我需要能够在我的app中的任何地方调用它们。我也做了很多参数检查,看是否应该允许/禁止该方法。

寻找有关此代码的建设性意见:

  • 关于重构params部分的任何想法?
  • 关于重构的任何想法可能会移出application_controller? (使其成为一种模型方法,但这不能重定向到某个网址/位置)

is_deleted方法:

  def is_deleted?
    if user_signed_in?
      if params[:action] != "reactivate" && 
         params[:action] != "destroy" && 
         params[:action] != "enable" && current_user.is_deleted == true
        redirect_to '/reactivate'
      end
    end
  end

is_banned?方法:

      def is_banned?
        if user_signed_in?
          if current_user.present? && current_user.banned?
            sign_out current_user
            flash[:error] = "Your account has been suspended for continued misbehaviour"
            redirect_to login_path
          end
        end
      end

1 个答案:

答案 0 :(得分:1)

将其移至模型是一个坏主意。渲染/重定向是控制器的工作。

这是代码的较短版本

def is_deleted?
  if user_signed_in? && !["reactivate", "destroy", "enable"].include?(params[:action]) && current_user.is_deleted
    redirect_to '/reactivate'
  end
end

def is_banned?
  if user_signed_in? && current_user.banned?
    sign_out(current_user) and redirect_to(login_path, :notice => "blah blah")
  end
end