Module: HstoreAccessor::TimeHelper

Defined in:
lib/hstore_accessor/active_record_pre_4.2/time_helper.rb

Class Method Summary collapse

Class Method Details

.string_to_time(string) ⇒ Object

There is a bug in ActiveRecord::ConnectionAdapters::Column#string_to_time which drops the timezone. This has been fixed, but not released. This method includes the fix. See: github.com/rails/rails/pull/12290



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/hstore_accessor/active_record_pre_4.2/time_helper.rb', line 7

def self.string_to_time(string)
  return string unless string.is_a?(String)
  return nil if string.empty?

  time_hash = Date._parse(string)
  time_hash[:sec_fraction] = ActiveRecord::ConnectionAdapters::Column.send(:microseconds, time_hash)
  year, mon, mday, hour, min, sec, microsec, offset = time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset)

  # Treat 0000-00-00 00:00:00 as nil.
  return nil if year.nil? || [year, mon, mday].all?(&:zero?)

  if offset
    time = Time.utc(year, mon, mday, hour, min, sec, microsec) rescue nil
    return nil unless time

    time -= offset
    ActiveRecord::Base.default_timezone == :utc ? time : time.getlocal
  else
    Time.public_send(ActiveRecord::Base.default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil
  end
end