关闭浏览器后,销毁或将全局变量设置为nil

时间:2023-02-14 00:18:52

I declared a global variable in my rails application controller as $decrypted_attessec = "verified decrypted cookie" and I am accessing it across all my controllers. Once I close the browser window, global variable must be set to nil or destroyed, which is not being done.

我在rails应用程序控制器中声明了一个全局变量,它是$decrypted_attessec =“经过验证的解密cookie”,我在所有的控制器中访问它。一旦我关闭浏览器窗口,全局变量必须设置为nil或销毁,这是不可能完成的。

In my case, it always holds initial value which is "verified decrypted cookie" in this case, however, server restart destroys the global variable and re-initialise it, which I want to be done on closing of browser too.

在我的例子中,它总是持有初始值,即“经过验证的解密cookie”,但是,服务器重启破坏了全局变量并重新初始化它,我也希望在关闭浏览器时也能这样做。

My code:

我的代码:

application_controller.rb

application_controller.rb

 def validate_user
    $decrypted_attessec = "verfied decrypted cookie"
      #I am getting value of $decrypted_attessec as verfied decrypted cookie from different action which would be either an empty or non-empty string
    if !$decrypted_attessec.empty?
      #redirect_to clicked path
    else
      redirect_to "login url"
    end
  end

Welcome_controller.rb < application_controller.rb

Welcome_controller。rb < application_controller.rb

if $decrypted_attessec.empty?
  before_action :validate_user, :except => [:index, :csplogin]
end

Where I went wrong with the code?

我的代码哪里出了问题?

1 个解决方案

#1


5  

First of all, @global_variable isn't a global variable at all. It is, in fact, an instance variable of an object of your class.

首先,@global_variable并不是一个全局变量。它实际上是类对象的实例变量。

Secondly, global variables are defined with a preceding $, for example, $global_variable. See this excellent post to read more about the implications of using global variables.

其次,全局变量定义为前面$,例如$global_variable。请参阅这篇优秀的文章以了解更多关于使用全局变量的含义。

Last, but not the least, global variables will not depend on closing and opening of the browser. I recommend elaborating your use-case more to get a better hit of solving your problem.

最后,但并非最不重要的是,全局变量不依赖于浏览器的关闭和打开。我建议详细描述您的用例,以便更好地解决您的问题。

#1


5  

First of all, @global_variable isn't a global variable at all. It is, in fact, an instance variable of an object of your class.

首先,@global_variable并不是一个全局变量。它实际上是类对象的实例变量。

Secondly, global variables are defined with a preceding $, for example, $global_variable. See this excellent post to read more about the implications of using global variables.

其次,全局变量定义为前面$,例如$global_variable。请参阅这篇优秀的文章以了解更多关于使用全局变量的含义。

Last, but not the least, global variables will not depend on closing and opening of the browser. I recommend elaborating your use-case more to get a better hit of solving your problem.

最后,但并非最不重要的是,全局变量不依赖于浏览器的关闭和打开。我建议详细描述您的用例,以便更好地解决您的问题。