重构类似方法重定向不同的Rails

时间:2017-03-28 14:57:52

标签: ruby-on-rails ruby-on-rails-3 redirect

我希望得到一些关于如何重构某些代码以使其更干燥的建议,因为Rails非常关注DRY。在我的控制器中,我有一些像这样的方法:

def filter
  if params[:status] == "All" && params[:department] == "All"
    redirect_to admin_organizations_path
  elsif params[:status] != "All" && params[:department] == "All"
    redirect_to admin_organizations_path(status: params[:status])
  elsif params[:status] == "All" && params[:department] != "All"
    redirect_to admin_organizations_path(department: params[:department])
  else
    redirect_to admin_organizations_path(status: params[:status], department: params[:department])
  end
end

def filter_manage
  if params[:status] == "All" && params[:department] == "All"
    redirect_to manage_organizations_path
  elsif params[:status] != "All" && params[:department] == "All"
    redirect_to manage_organizations_path(status: params[:status])
  elsif params[:status] == "All" && params[:department] != "All"
    redirect_to manage_organizations_path(department: params[:department])
  else
    redirect_to manage_organizations_path(status: params[:status], department: params[:department])
  end
end

def filter_index
  if params[:department] == "All"
    redirect_to organizations_path
  else
    redirect_to organizations_path(department: params[:department])
  end
end

def filter_user
  if params[:department] == "All"
    redirect_to user_organizations_path
  else
    redirect_to user_organizations_path(department: params[:department])
  end
end

正如您所看到的,唯一真正的区别在于它们重定向到的位置,如何将其变为可重用的代码片段,智能地知道在何处重定向到给定视图的来源,因为这些方法是只是重定向回到他们来自的视图。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

我相信你可以这样做:

def filter(flag)
    if params[:status] == "All" && params[:department] == "All"
        myparams = {}
    elsif params[:status] != "All" && params[:department] == "All"
        myparams = {status: params[:status]}
    elsif params[:status] == "All" && params[:department] != "All"
        myparams = {department: params[:department]}
    else
        myparams = {status: params[:status], department: params[:department]}
    end
    ## flag = 0 -> manage_organizations_path
    ## flag = 1 -> admin_organizations_path
    if flag
        admin_organizations_path(myparams)
    else
        manage_organizations_path(myparams)
    end
end

答案 1 :(得分:1)

你可以通过简单地迭代params哈希并保留那些匹配测试的参数来简化这个过程:

def filter_params(*keys)
  params.slice(keys).keep_if do |key, value|
    value.present? && value != "All"
  end
end

def filter
  redirect_to admin_organizations_path(filter_params(:status, :department))
end

def filter_manage
  redirect_to admin_organizations_path(filter_params(:status, :department))
end

def filter_index
  redirect_to organizations_path(filter_params(:department))
end

def filter_user
  redirect_to user_organizations_path(filter_params(:department))
end