使用空对象模式进行设计的访客用户

问题描述 投票:2回答:1

我正在尝试在设计中实现一个Guest用户,但是这样做user_signed_in?总是评估为true我该如何解决?

我不能使用signed_in?,因为我同时具有AdminUser,因此,如果我在管理面板上登录,然后转到主网站,它会认为我在使用[[ C0]

这里是代码

应用程序控制器

signed_in?

查看

def current_user
  if devise_controller?
    @current_user = super
  else
    @current_user ||= super || Guest.new
  end
end

更新

我已经决定重写<p>Welcome <strong><%= current_user.first_name %></strong></p> <ul> <% if user_signed_in? %> <li> <%= link_to 'Sign out', destroy_user_session_path, method: :delete %> </li> <% else %> <li><%= link_to 'Sign up', new_user_registration_path %></li> <li><%= link_to 'Sign in', new_user_session_path %></li> <% end %> </ul> 方法,而且user_signed_in?破坏了我的测试,所以我把它取出来,将if devise_controller?更改为现在的样子。

应用程序控制器

ApplicationController
ruby-on-rails ruby authentication ruby-on-rails-4 devise
1个回答
0
投票

Devise在此处定义def current_user @current_user ||= super || Guest.new end def user_signed_in? current_user.is_a? User end

user_signed_in?

在这种情况下,您只需将 def self.define_helpers(mapping) #:nodoc: mapping = mapping.name class_eval <<-METHODS, __FILE__, __LINE__ + 1 def authenticate_#{mapping}!(opts={}) opts[:scope] = :#{mapping} warden.authenticate!(opts) if !devise_controller? || opts.delete(:force) end def #{mapping}_signed_in? !!current_#{mapping} end def current_#{mapping} @current_#{mapping} ||= warden.authenticate(scope: :#{mapping}) end def #{mapping}_session current_#{mapping} && warden.session(:#{mapping}) end METHODS ActiveSupport.on_load(:action_controller) do if respond_to?(:helper_method) helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session" end end end 方法添加到!类中>

Guest
© www.soinside.com 2019 - 2024. All rights reserved.