我可以在离开范围时触发清理吗



有时我发现自己需要将上下文附加到特定的作用域,在作用域退出后释放它,例如

User.all do |u|
  custom_logger.with_context({ user_id: u.id }) do
    # .. some code
    custom_logger.warn('something happened')
    # .. some more code
  end
end

你可以在铁轨上看到这种模式,例如

I18n.with_locale(...) do
  # some code
end

我想要类似的行为,但一旦我退出当前范围,可能会进行清理,例如

User.all do |u|
  custom_logger.set_scoped_context({ user_id: u.id })
  # .. some code
  custom_logger.warn('something happened')
  # .. some more code
end 

在上面的代码中,我希望行为与前面的示例类似,但上下文的范围是周围的范围。

这有可能在ruby中实现吗?

更改全局状态并期望一些隐藏的抽象来清除/重置状态是非常容易出错的。如果您不喜欢块样式,我建议您使用当前上下文创建一个新的记录器,而不是更改全局状态:

User.all do |u|
  scoped_logger = custom_logger.with_context({ user_id: u.id })
  # .. some code
  scoped_logger.warn('something happened')
  # .. some more code
end

最新更新