Rails DRY问题:在控制器和视图中需要相同的代码

时间:2011-04-23 03:57:18

标签: ruby-on-rails ruby-on-rails-3 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 %>

您如何建议解决此问题?我应该在哪里定义confirm_logged_in

1 个答案:

答案 0 :(得分:5)

您可以使用helper_method

<强> controller.rb

helper_method :confirm_logged_in, :current_user

protected

def confirm_logged_in
  # code...
end

def current_user
  # code...
end