Class: ActiveGraph::Shared::TypeConverters::DateTimeConverter

Inherits:
BaseConverter
  • Object
show all
Defined in:
lib/active_graph/shared/type_converters.rb

Overview

Converts DateTime objects to and from Java long types. Must be timezone UTC.

Class Method Summary collapse

Methods inherited from BaseConverter

converted?, #supports_array?

Class Method Details

.convert_typeObject


139
140
141
# File 'lib/active_graph/shared/type_converters.rb', line 139

def convert_type
  DateTime
end

.db_typeObject


143
144
145
# File 'lib/active_graph/shared/type_converters.rb', line 143

def db_type
  Integer
end

.to_db(value) ⇒ Object

Converts the given DateTime (UTC) value to an Integer. DateTime values are automatically converted to UTC.


149
150
151
152
153
154
155
156
# File 'lib/active_graph/shared/type_converters.rb', line 149

def to_db(value)
  value = value.new_offset(0) if value.respond_to?(:new_offset)

  args = [value.year, value.month, value.day]
  args += (value.class == Date ? [0, 0, 0] : [value.hour, value.min, value.sec])

  Time.utc(*args).to_i
end

.to_ruby(value) ⇒ Object


158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/active_graph/shared/type_converters.rb', line 158

def to_ruby(value)
  return value if value.is_a?(DateTime)
  t = case value
      when Time
        return value.to_datetime.utc
      when Integer
        Time.at(value).utc
      when String
        return value.to_datetime
      else
        fail ArgumentError, "Invalid value type for DateType property: #{value.inspect}"
      end

  DateTime.civil(t.year, t.month, t.day, t.hour, t.min, t.sec)
end