2012-05-28 2 views
0

저는 Ruby on Rails에서 인증을 위해 Devise을 사용하고 있습니다. 사용자 업데이트를 위해 현재 비밀번호가 필요없는 등록 업데이트 컨트롤러를 무시하고 있습니다. 따라서 기본적으로 아래 코드는 "사용자가 암호를 제공하지 않으면 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 

분명히, 여기에 코드 중복을 줄일 수있는 여지가있다,하지만, 난 여전히 루비에 새로 온 사람과 사람이 중첩 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

Perfect! 그게 바로 제가 찾던 것입니다.'Ruby '방법으로는 알지 못했습니다. – Paul