减少Ruby on Rails中的冗余代码

时间:2012-05-28 15:50:49

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

我在Ruby on Rails中使用Devise进行身份验证,并且我正在覆盖注册更新控制器,以便不需要当前密码来更新User模型。所以,基本上下面的代码说“如果用户没有提供密码,请使用update_without_password进行更新,否则使用update_attributes更新”。

if resource_params["password"].empty?

    if resource.update_without_password(resource_params)
      if is_navigational_format?
        if resource.respond_to?(:pending_reconfirmation?) && resource.pending_reconfirmation?
          flash_key = :update_needs_confirmation
        end
        set_flash_message :notice, flash_key || :updated
      end
      sign_in resource_name, resource, :bypass => true
      respond_with resource, :location => after_update_path_for(resource)
    else
      clean_up_passwords resource
      respond_with resource
    end

else

    if resource.update_attributes(resource_params)
      if is_navigational_format?
        if resource.respond_to?(:pending_reconfirmation?) && resource.pending_reconfirmation?
          flash_key = :update_needs_confirmation
        end
        set_flash_message :notice, flash_key || :updated
      end
      sign_in resource_name, resource, :bypass => true
      respond_with resource, :location => after_update_path_for(resource)
    else
      clean_up_passwords resource
      respond_with resource
    end

end 

显然,这里有减少代码冗余的空间,但我仍然是ruby的新手,并且想知道是否有人可以建议一种干净的方式来编写相同的东西而不复制嵌套if中的所有代码

谢谢!

1 个答案:

答案 0 :(得分:1)

如果我正确地读你,并且没有遗漏任何东西,那里只有一条不同的区别。你可以这样写:

result = if resource_params["password"].empty?
    resource.update_without_password(resource_params)
  else 
    resource.update_attributes(resource_params)
  end

if result
  if is_navigational_format?
    if resource.respond_to?(:pending_reconfirmation?) && resource.pending_reconfirmation?
      flash_key = :update_needs_confirmation
    end
    set_flash_message :notice, flash_key || :updated
  end
  sign_in resource_name, resource, :bypass => true
  respond_with resource, :location => after_update_path_for(resource)
else
  clean_up_passwords resource
  respond_with resource
end
相关问题