【问题标题】:Can my app be notified when a session is destroyed? If so, how?会话被销毁时可以通知我的应用程序吗?如果是这样,怎么做?
【发布时间】:2011-07-25 18:28:15
【问题描述】:

我的基于 Devise/Warden 的应用程序将模型 ID 存储在 session[] 变量中。我想在 session[] 被销毁时销毁对象。

  • 当会话被销毁时,是否有回调或某种机制来通知我的应用程序?
  • 该机制是否可靠,或者我应该运行一个夜间清理脚本来清理所有孤立对象?

为了清楚起见,这是我的控制器代码的 sn-p:

class WizardsController < ApplicationController
  before_filter :find_or_create_wizard
  ...
private

  def find_or_create_wizard
    @wizard = Wizard.find_by_id(session[:wizard_id]) || Wizard.create.tap {|w| session[:wizard_id] = w }
  end

end

重申问题:我应该如何以及何时销毁 Wizard 对象?

【问题讨论】:

    标签: ruby-on-rails-3 session devise warden


    【解决方案1】:
    Warden::Manager.before_logout do |user,auth,opts| 
      # callback 
    end 
    

    使用 Warden::Hooks https://github.com/hassox/warden/blob/master/lib/warden/hooks.rb 在退出或验证后执行操作。

    【讨论】:

    • 正如一位著名的拉里常说的“poifect”!
    【解决方案2】:

    会话是指用户注销的时候吗?

    尝试在 application_controller.rb 中修补 sign_out 方法 您可以在lib/devise/controllers/helpers.rb中找到相关的Gem代码

    def sign_out(resource_or_scope=nil)
        Wizard.find_by_id(session[:wizard_id]) || Wizard.create.tap {|w| session[:wizard_id] = w }
        super(resource_or_scope)
    end
    

    每当用户通过名为expire_session_data_after_sign_in! 的函数登录或注册时,会话数据也会被清除,也可以覆盖它:

    def expire_session_data_after_sign_in!
            Wizard.find_by_id(session[:wizard_id]) || Wizard.create.tap {|w| session[:wizard_id] = w }
            super
    end
    

    【讨论】:

    • 通过“会话”,我的意思是我需要什么机制来避免随着时间的推移泄漏向导对象:我在当前会话中创建了一个单例向导对象,我只是想知道何时删除它。我想你的解决方案会起作用,但我希望找到一种不需要修补系统的技术。
    • 似乎不是 sign_out 操作的内置回调(我没有提取最新的来源)。我所有的设计调整都涉及猴子补丁。对于 Ruby 来说,这并没有什么特别之处。如果您对此非常担心,可以设置一个延迟作业来为您执行此操作。我可能只会使用 DJ。
    猜你喜欢
    • 2023-04-07
    • 2012-04-08
    • 2021-06-30
    • 2011-01-21
    • 1970-01-01
    • 2017-11-14
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多