1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
module OneTimeZone
  module ActiveRecordMethods

    # def self.extended(base)
    #   puts "extending #{base.inspect}"
    #   base.module_eval do
    #     def self.inherited(subclass)
    #       puts "inherited #{subclass}"
    #         attributes=columns.select { |c| c.type ==:datetime }.map(&:name)
    #         tz_time_attributes attributes
    #     end
    #   end        
    # end
    
    def one_time_zone(options={})
      class_inheritable_array :tz_attributes, :instance_writer => false
      self.tz_attributes =columns.select { |c| c.type ==:datetime }.map(&:name)
      class_eval do
        tz_attributes.each do |attribute|
          define_method attribute do
            time = read_attribute(attribute)
            if (time.acts_like?(:time) || time.acts_like?(:date))# && time.utc?
              time=time.utc
              write_attribute(attribute, time.in_current_time_zone)
            else
              time
            end
          end
        end        
        
       protected
          def fix_timezone
            tz_attributes.each do |attribute|
              send attribute.to_sym
            end
          end
      end
      # we need to do this in both since if they save(false) we still
      # want the proper time to be saved to the database
      before_validation :fix_timezone
      before_save :fix_timezone
    end
    
  end
end