Skip to content

Instantly share code, notes, and snippets.

@narath
Forked from bkeepers/application.js
Last active February 16, 2021 20:41
Show Gist options
  • Select an option

  • Save narath/c6331e18b0689e9623d73f8d033c247c to your computer and use it in GitHub Desktop.

Select an option

Save narath/c6331e18b0689e9623d73f8d033c247c to your computer and use it in GitHub Desktop.

Revisions

  1. narath revised this gist Feb 16, 2021. 2 changed files with 17 additions and 6 deletions.
    7 changes: 4 additions & 3 deletions application.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,4 @@
    jQuery(function() {
    $.cookie('tz', (new Date()).getTimezoneOffset());
    });
    // jquery-cookies retired, moved this to js-cookie which no longer requires jQuery
    import Cookies from 'js-cookie'

    Cookies.set('tz', (new Date()).getTimezoneOffset());
    16 changes: 13 additions & 3 deletions application_controller.rb
    Original file line number Diff line number Diff line change
    @@ -5,10 +5,20 @@ class ApplicationController < ActionController::Base
    private

    def set_timezone
    if current_user && browser_timezone && browser_timezone.name != current_user.time_zone
    current_user.update_attributes :time_zone => browser_timezone.name
    # if the user has set their time_zone we default to that
    # if there is no user.time_zone set, then we default to the browser time_zone
    if current_user
    if current_user.time_zone
    Time.zone = current_user.time_zone
    logger.info("Using current_user.time_zone #{current_user.time_zone}")
    elsif browser_timezone
    Time.zone = browser_timezone
    logger.info("Using browser_timezone since current_user does not have time_zone set")
    end
    elsif browser_timezone
    Time.zone = browser_timezone
    logger.info("Not logged in, so using browser_timezone")
    end
    Time.zone = current_user ? current_user.time_zone : browser_timezone
    end

    def browser_timezone
  2. @bkeepers bkeepers created this gist Mar 3, 2010.
    3 changes: 3 additions & 0 deletions application.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    jQuery(function() {
    $.cookie('tz', (new Date()).getTimezoneOffset());
    });
    20 changes: 20 additions & 0 deletions application_controller.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    class ApplicationController < ActionController::Base
    before_filter :set_timezone

    # …
    private

    def set_timezone
    if current_user && browser_timezone && browser_timezone.name != current_user.time_zone
    current_user.update_attributes :time_zone => browser_timezone.name
    end
    Time.zone = current_user ? current_user.time_zone : browser_timezone
    end

    def browser_timezone
    @browser_timezone ||= begin
    ActiveSupport::TimeZone[-cookies[:tz].to_i.minutes]
    end if cookies[:tz].present?
    end

    end