From 94b2c256b907182a5e4ac320a3728a99187676e5 Mon Sep 17 00:00:00 2001 From: Kevin McConnell Date: Mon, 27 Jan 2025 14:16:15 +0000 Subject: [PATCH] Set request timezone to match browser --- app/controllers/application_controller.rb | 2 +- app/controllers/concerns/current_timezone.rb | 17 +++++++++++++++++ .../controllers/timezone_cookie_controller.js | 12 ++++++++++++ app/views/layouts/application.html.erb | 2 +- 4 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 app/controllers/concerns/current_timezone.rb create mode 100644 app/javascript/controllers/timezone_cookie_controller.js diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index c54063eef..4f75453ff 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,5 +1,5 @@ class ApplicationController < ActionController::Base - include Authentication + include Authentication, CurrentTimezone stale_when_importmap_changes allow_browser versions: :modern diff --git a/app/controllers/concerns/current_timezone.rb b/app/controllers/concerns/current_timezone.rb new file mode 100644 index 000000000..9c36757c8 --- /dev/null +++ b/app/controllers/concerns/current_timezone.rb @@ -0,0 +1,17 @@ +module CurrentTimezone + extend ActiveSupport::Concern + + included do + around_action :set_current_timezone + end + + private + def set_current_timezone(&) + Time.use_zone(timezone_from_cookie, &) + end + + def timezone_from_cookie + timezone = cookies[:timezone] + timezone if timezone.present? && ActiveSupport::TimeZone[timezone] + end +end diff --git a/app/javascript/controllers/timezone_cookie_controller.js b/app/javascript/controllers/timezone_cookie_controller.js new file mode 100644 index 000000000..f469a3f8f --- /dev/null +++ b/app/javascript/controllers/timezone_cookie_controller.js @@ -0,0 +1,12 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + connect() { + this.#setTimezoneCookie() + } + + #setTimezoneCookie() { + const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone + document.cookie = `timezone=${encodeURIComponent(timezone)}; path=/` + } +} diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 251af449a..3a4b0e53e 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -19,7 +19,7 @@ <%= yield :head %> - +