2013-09-27 46 views
0

我正在學習重構我的代碼,但我在重構session_controller時遇到了麻煩,這是我的應用程序中的問題。它違反了「tell do not ask」原則。我正在考慮提取一些邏輯到它自己的類,但不知道如何工作。這裏是來自控制器的代碼。在Ruby On Rails中重構sessions_controller

class SessionsController < ApplicationController 
    def create 
    admin = Admin.find_by(email: params[:sessions][:email]) 
    if admin && admin.authenticate(params[:sessions][:password]) 
     sign_in admin 
     redirect_to anasayfa_path 
     flash[:success] = 'Başarılı şekilde giriş yapıldı' 
    else 
     redirect_to root_path 
     flash[:error] = 'Giriş bilgilerinde bir hata var' 
    end 
    end 
end 

我將如何重構呢?我認爲此方法提取

admin && admin.authenticate(params[:sessions][:password]) 

,但是那會是最好的辦法?我會在哪裏把類,如果我這個提取?

回答

1

首先,您可以提取管理查找,因爲它可能會在其他操作中重用。

此外,您可以標準化您的閃存密鑰:noticealert#redirect_to明白的兩個標準密鑰。

class SessionsController < ApplicationController 
    before_filter :find_admin 

    def create 
    if @admin.authenticate(params[:sessions][:password]) 
     sign_in @admin 
     redirect_to anasayfa_path, notice: 'Başarılı şekilde giriş yapıldı' 
    else 
     redirect_to root_path, alert: 'Giriş bilgilerinde bir hata var' 
    end 
    end 

    private 

    def find_admin 
    @admin = Admin.where(email: params[:sessions][:email]).first or redirect_to(root_path, alert: 'not logged in') 
    end 
end 

你必須使用#where,而不是#find_by避免異常,如果找不到管理員。從#find_admin#redirect_to

ActionController::Flash.add_flash_types(:success, :error) 

路徑,當認證失敗或許應該指出登錄網址:

如果你想保持你當前的閃光燈鍵,您可以添加在初始化。

0

試試這個

class SessionsController < ApplicationController 
    def create 
    admin = Admin.find_by(email: params[:sessions][:email]) 
    login_status = false 
    if admin && admin.authenticate(params[:sessions][:password]) 
     sign_in admin 
     login_status = true 
    end 
    login_status ? redirect_to(anasayfa_path, :flash => {:success => 'Başarılı şekilde giriş yapıldı'}) : redirect_to(root_path, :flash => {:error => 'Giriş bilgilerinde bir hata var'}) 
    end 
end