发布 Gon v7.0.0
发布: (2026年1月11日 GMT+8 14:29)
2 min read
原文: Dev.to
Source: Dev.to
发布 v7.0.0
Gon v7.0.0 发布 – 此次重大版本升级引入了不兼容的更改。
重大变更:request_store 现在是可选的
已移除对 request_store 的依赖。当可用时,Gon 更倾向于使用 ActiveSupport::CurrentAttributes。
背景
- 以前,像
gon.foo = 'bar'这样的赋值会使用request_store在内部存储值。 - 自 Rails 5.2 起,Rails 提供了官方的替代方案 ActiveSupport::CurrentAttributes。
request_store依赖于Thread#[],实际上使用的是 fiber‑local 变量。当执行切换到另一个 Fiber 时,可能导致行为不正确。- 早期的
ActiveSupport::CurrentAttributes也使用 fiber‑local 存储,但从 Rails 7.0 开始,它会根据服务器类型自动在 fiber‑local 与 thread‑local 之间切换,从而更为稳定。
新行为
| 条件 | Gon 的存储机制 |
|---|---|
Rails 5.2+ 且 ActiveSupport::CurrentAttributes 可用 | ActiveSupport::CurrentAttributes(自动) |
| 否则 | request_store(必须显式添加) |
如果需要在旧版 Rails 中使用 request_store,请将其添加到 Gemfile:
# Gemfile
gem 'request_store'
该怎么做
- 对于大多数现代 Rails 应用(Rails 5.2+),无需更改——Gon 将自动使用
ActiveSupport::CurrentAttributes。 - 如果遇到任何问题或仍依赖旧行为,请告知维护者。