Module: TimezoneField::ClassMethods

Defined in:
lib/timezone_field.rb

Instance Method Summary collapse

Instance Method Details

#define_timezone_accessors(field_name) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/timezone_field.rb', line 23

def define_timezone_accessors(field_name)
  define_method(:"#{field_name}") do
    mapping = ActiveSupport::TimeZone::MAPPING
    zone_str = read_attribute(field_name)
    if mapping.has_key?(zone_str)
      rails_zone_identifier = zone_str
    else
      rails_zone_identifier = mapping.invert[zone_str] || Time.zone.name
    end
    ActiveSupport::TimeZone[rails_zone_identifier]
  end
  define_method(:"#{field_name}=") do |tz|
    zone = tz && ActiveSupport::TimeZone[tz]
    if zone
      write_attribute(field_name, zone.tzinfo.name)
    else
      write_attribute(field_name, tz) # This will produce a validation error when you try to save
    end
  end
end

#has_timezone_field(field_name) ⇒ Object



17
18
19
20
21
# File 'lib/timezone_field.rb', line 17

def has_timezone_field(field_name)
  self.timezone_fields << field_name
  define_timezone_accessors(field_name)
  validates :"#{field_name}", :zone => true
end