Sinatra为每个请求安全设置时区

问题描述

我试图找出如何在多线程应用程序的Sinatra中按请求设置时区。

Rails提供了:around_action过滤器来处理此请求,其中请求是在Time.use_zone块内处理的。

around_action :set_time_zone,if: :current_user

def set_time_zone(&block)
  Time.use_zone(current_user.time_zone,&block) 
end

Sinatra,仅提供过滤器之前和之后:

before do
  Time.zone = current_user.time_zone
end

after do
  Time.zone = default_time_zone
end

但是,这种方法似乎不是线程安全的。在Sinatra中实现此目标的正确方法是什么?

解决方法

我记得有一个Sinatra扩展来提供around钩子,但是找不到。否则,您必须将代码放入每个动作中:

def my_endpoint
  with_around_hooks do
    render text: "hello world"
  end
end

private

def with_around_hooks(&blk)
  # you could hypothetically put more stuff here
  Time.use_zone(current_user.time_zone,&blk) 
end

希望其他人知道一种将代码包装在每个请求周围的方法