0

Devise在 Ruby on Rails 中用于身份验证,并且我正在覆盖注册更新控制器,以不需要当前密码来更新 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

谢谢!

4

1 回答 1

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
于 2012-05-28T15:54:52.217 回答