0

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​​ に慣れていないので、ネストされた .xml 内のすべてのコードを複製せずに同じことを書くためのクリーンな方法を誰かが提案できるかどうか疑問に思っていましたif

ありがとう!

4

1 に答える 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 に答える