0

我试图弄清楚如何在 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 中完成此任务的正确方法是什么?

4

1 回答 1

0

我记得有一个 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

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

于 2020-10-10T01:00:45.157 回答