Skip to content

Instantly share code, notes, and snippets.

@davidlee
Created October 20, 2009 23:31
Show Gist options
  • Save davidlee/214718 to your computer and use it in GitHub Desktop.
Save davidlee/214718 to your computer and use it in GitHub Desktop.
# assumes a User model with restful_authentication and a string time_zone column
class ApplicationController < ActionController::Base
around_filter :set_timezone
def set_timezone
TzTime.zone = TimeZone[ current_user && current_user.time_zone || session[:utc_offset_hours] || 0 ]
yield
TzTime.reset!
end
end
class ApplicationHelper
# print UTC time (eg record created_at timestamps) as localtime for the current user
def tz(time)
if current_user && current_user.time_zone
TzTime.zone.utc_to_local(time.utc)
else
time.to_time.utc + (session[:utc_offset_hours] || 0).hours
end
end
end
// global.js
$(document).ready(function() {
// set the local timezone as per the browser's idea of local time
var t = new Date();
// expects ENV.timezoneOffset to be returned by server once set in session
// otherwise this post happens on each request
if(ENV.timezoneOffset != t.getTimezoneOffset())
$.post('/time_zone', { format: 'json', _method: 'put', utc_offset: t.getTimezoneOffset() });
});
# timezone controller accepts an initial JS post giving the offset, also allows the user to specify their 'real' timezone via a drop-down
class TimeZoneController < ApplicationController
skip_before_filter :load_announcements, :only => ['update']
skip_before_filter :verify_authenticity_token, :only => ['update']
def update
respond_to do |format|
format.json do
# session[:javascript_utc_offset] = params[:utc_offset];
session[:utc_offset_hours] = (params[:utc_offset].to_i / 60).abs
render :nothing => true, :status => 204, :content_type => 'application/json'
end
format.any do
verify_authenticity_token
if params[:time_zone] && TimeZone[params[:time_zone]]
current_user.time_zone = params[:time_zone]
current_user.save!
flash[:notice] = "Thank you. Your time zone is now set to #{params[:time_zone]}"
redirect_to '/'
else
flash[:warning] = "Failed to set time zone. Please try again."
edit
render :action => 'edit'
end
end
end
end
def edit
@time_zones = TimeZone.all.sort_by(&:utc_offset)
end
end
# time_zone/edit.html.haml
%h3.green-type Set your local Time Zone
%form{:action => '/time_zone', :method => 'POST'}
%input{:type => 'hidden', :name => 'authenticity_token', :value => form_authenticity_token}
%input{:type => 'hidden', :name => '_method', :value => 'PUT'}
%p
%label{:for => 'time_zone'} Choose your local time zone from the list:
%p.input
%select{:name => 'time_zone'}
- @time_zones.each do |zone|
%option{:value => zone.name, :selected => zone == TzTime.zone}= zone
%p.input
%input.green{:type => 'submit', :value => 'Remember my Time Zone'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment