2011-04-23 25 views
0

需要相同的代碼,我在我的網頁以下登錄檢查:Rails的DRY問題:在控制器和視圖

class LoungeController < ApplicationController 
    before_filter :confirm_logged_in 
    def index 
    end 
end 

confirm_logged_in定義在這裏:

class ApplicationController < ActionController::Base 
    protect_from_forgery 

    protected 

    def confirm_logged_in 
    return true if current_user 
    redirect_to(:controller => 'access', :action => 'login') 
    return false # halts the before_filter 
    end 

    def current_user 
    return false unless session[:user_id] 
    user = User.find(session[:user_id]) 
    return false unless user 
    (user.display_name == session[:user_display_name]) ? user : nil 
    end 
end 

現在,我想用confirm_logged_in也在app/views/layouts/application.html.erb

<% if confirm_logged_in %> 
    <div id="logged_in_as">You are logged in as <%= session[:user_display_name] %></div> 
    <div id="logout"><%= link_to("Logout", {:controller => "access", :action => "logout"}, :id => "logout_link") %></div> 
<% end %> 

你會如何表示st解決這個問題?我應該在哪裏定義confirm_logged_in

回答

5

您可以使用helper_method

controller.rb

helper_method :confirm_logged_in, :current_user 

protected 

def confirm_logged_in 
    # code... 
end 

def current_user 
    # code... 
end 
+0

完美解決方案:)謝謝! – 2011-04-23 07:55:36