Module: TZTime::ActiveRecord::Acts::LocalTime::ClassMethods

Defined in:
lib/tztime/activerecord/acts/local_time.rb

Overview

This acts provides the capabilities for storing time zones and using them to generate and convert times. This requires that ActiveRecord be configured to store times in utc. Requiring tztime/activerecord will configure ActiveRecord itself.

This will add a composed_of property using the name provided by the :time_builder_accessor (defaults to :local_time_builder) and gets the time zone name from the :time_zone_field option (defaults to :time_zone).

All methods that return a Time or DateTime object gain the ability to be localized to the timezone used by the model instance. For example, a created_at field value can be localized via local_created_at. This is not limited to field accessors; custom methods also gain this capability. For example: class Foo < ActiveRecord::Base acts_as_time_zone

def bar Time.now # will be in UTC end end

A localized value of bar can be accessed via local_bar. This value will be converted into a TZTime::LocalTime instance with the time zone set in the Foo instance.

Parameters

options<Hash>

See below.

Options

:time_zone_field<Symbol,String>

The field in the database that holds the time zone name. Default :time_zone

:time_builder_accessor<Symbol,String>

The name of the composed_of field to create to access the local time builder instance. Default :local_time_builder

Usage

Create a migration that includes a time_zone field :

class CreateSettings < ActiveRecordMigration
  def self.up
    create_table :settings do |t|
      t.string :time_zone
      t.timestamps
    end
  end
end

Define the Setting model:

require 'tztime/activerecord'

class Setting < ActiveRecord::Base
  acts_as_time_zone
end

Create an instance and get the current date and time

setting = Setting.create :time_zone => 'Eastern Time (US & Canada)'
setting.time_zone_builder.now
setting.created_at # => time in UTC
setting.local_created_at # => time in EDT or EST

Instance Method Summary collapse

Instance Method Details

#acts_as_local_time(options = {}) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/tztime/activerecord/acts/local_time.rb', line 72

def acts_as_local_time(options={})
  options = {
    :time_zone_field => :time_zone,
    :time_builder_accessor => :local_time_builder
  }.merge(options)
  
  write_inheritable_attribute(:acts_as_local_time_options, options)
  class_inheritable_reader :acts_as_local_time_options
  
  if options[:time_builder_accessor] && options[:time_zone_field]
    composed_of(options[:time_builder_accessor].to_sym, {
	    :class_name => 'TZTime::LocalTime::Builder',
	    :mapping => %W{#{options[:time_zone_field]} time_zone_name}
	  })
  end

	include InstanceMethods
end