Rails 有办法在请求之间重置类变量吗?

发布于 2024-12-15 02:14:20 字数 808 浏览 3 评论 0原文

我意识到 当考虑 ActiveResource::Base 中的用户、密码和站点变量时,它们可以在一次请求时进行修改,并在下一次请求时保持修改状态。这似乎是不受欢迎的行为,并且可能是一个普遍存在的问题,因为它适用于类变量/属性的所有使用。

Rails 是否提供了一种机制来清除类级别状态的更改(例如重置为默认值),以便每个请求都以原始状态启动?

如果没有,是否可以添加一种初始化类变量的方法,该方法将在每个请求开始时重新应用?这可以与线程安全存储相结合,从而减少类变量的问题。是否可以修改 class_attribute

更新:

正如我在上面的链接问题,引起我注意的具体情况是我在每个用户的基础上设置 ActiveResource::Base.user 和密码。如果我未能重置它们,则意味着在后续页面加载时将使用另一个用户的凭据代表一个用户发出 REST 请求。

I realized when thinking about the user, password, and site variables in ActiveResource::Base, that they could be modified on one request and would remain modified on the next request. That seems like undesirable behavior, and possibly a widespread problem, since it applies to all use of class variables / attributes.

Does Rails provide a mechanism for cleaning up changes to class-level state (e.g. reset to default) so that each request starts in a pristine condition?

If not, would it be possible to add a way of initializing class variables which would get re-applied at the beginning of each request? This could be combined with thread-safe storage, making class variables much less problematic. A possible modification of class_attribute?

Update:

As I described in the linked question above, the specific case that brought this to my attention was the fact that I was setting ActiveResource::Base.user and password on a per-user basis. If I ever failed to reset them, that would mean that REST requests on behalf of one user would be made using the credentials of another on subsequent page loads.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

魄砕の薆 2024-12-22 02:14:20

出于好奇,您能举一个具体的例子来说明为什么要这样做吗?从表面上看,听起来您正在请求更改变量,因此 Rails 正在执行您所要求的操作。

至于答案,有几个选择:

  • 变量没有自动“切换回默认”行为,没有。
  • 您可以在希望发生这种情况的每个控制器操作末尾手动重置值
  • 您可以编写一个执行此操作的模块(称为“acts_as_resettable”?),然后将该模块包含在您想要此功能的类中

Just out of curiosity, can you give a concrete example of why you want to do this? On the face of it, it sounds like you're requesting a change to a variable, so Rails is doing what you're asking for.

As far as an answer, a few options:

  • There's no automatic "switch back to default" behavior for variables, no.
  • You could manually reset the values at the end of each controller action where you want this to happen
  • You could write a module that does this (called it, "acts_as_resettable"?), and then include that module in the classes where you want this functionality
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文