0

I'm trying to figure out how to set the timezone on a per request basis in Sinatra for a multithreaded application.

Rails provides the :around_action filter to handle this wherein the request is processed inside of a Time.use_zone block.

around_action :set_time_zone, if: :current_user

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

Sinatra, however, only provides before and after filters:

before do
  Time.zone = current_user.time_zone
end

after do
  Time.zone = default_time_zone
end

That approach, however, does not seem threadsafe. What is the right way to accomplish this in Sinatra?

fny
  • 31,255
  • 16
  • 96
  • 127
  • 1
    Does this answer your question? [Setting Time.zone during a request: Thread Safe?](https://stackoverflow.com/questions/15451637/setting-time-zone-during-a-request-thread-safe) – Sara Fuerst Oct 09 '20 at 20:57

1 Answers1

1

I recall there being a Sinatra extension to provide around hooks, but can't find it. Otherwise, you'd have to put the code in each action:

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

Hopefully someone else knows a way to wrap code around each request though

max pleaner
  • 26,189
  • 9
  • 66
  • 118