2012-05-28 53 views
0

我在使用Devise進行Ruby on Rails中的認證,並且我重寫了註冊更新控制器,不需要用戶模型更新的當前密碼。所以,基本上下面的代碼說「如果用戶不提供密碼,使用update_without_password更新,否則使用update_attributes更新」。減少Ruby on Rails中的冗餘代碼

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

如果我正在閱讀你的文章並且沒有遺漏任何東西,那麼這裏只有一條線。你可以這樣寫:

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 
+0

完美!這正是我所尋找的,只是不知道'Ruby'的方式。 – Paul