Skip to content

Instantly share code, notes, and snippets.

@billymeltdown
Created March 23, 2009 19:47
Show Gist options
  • Save billymeltdown/83735 to your computer and use it in GitHub Desktop.
Save billymeltdown/83735 to your computer and use it in GitHub Desktop.
class UpdateTimestampFieldsToUtc < ActiveRecord::Migration
cattr_accessor :use_utc
def self.up
transaction do
@@use_utc = true
adjust_models
end
end
def self.down
transaction do
@@use_utc = false
adjust_models
end
end
class << self
def adjust_models
adjust_fields(Task, ['created_at', 'start_at', 'stop_at'])
adjust_fields(Order, ['created_at'])
adjust_fields(Project, ['created_at'])
adjust_fields(User, ['created_at', 'activated_at', 'remember_token_expires_at'])
end
def adjust_fields(model, fields)
# for each of this model's objects
model.all.each do |obj|
# build a set of updates
updates = []
fields.each do |f|
# go to either utc or eastern, based on setting of @use_utc
unless obj.send(f.to_sym).blank?
# do a direct db update to avoid active record translation to utc!
interval = @@use_utc ? adjust_to_utc(obj.send(f.to_sym)) : adjust_to_eastern(obj.send(f.to_sym))
updates << "#{f} = #{f} + '#{interval} hours'::interval"
end # unless
end # fields.each
unless updates.empty?
sql = "UPDATE #{model.table_name} SET #{updates.join(', ')} WHERE id = #{obj.id};"
puts sql
ActiveRecord::Base.connection.execute(sql)
end
end # model.each
end
def adjust_to_utc(time)
time.dst? ? 4 : 5
end
def adjust_to_eastern(time)
time.dst? ? -4 : -5
end
end # class << self
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment