Class: ActiveModel::Type::Time

Inherits:
Value
  • Object
show all
Includes:
Helpers::TimeValue, Helpers::Timezone
Defined in:
lib/active_model/type/time.rb

Overview

Active Model Time Type

Attribute type for time of day representation. It is registered under the :time key.

class Event
  include ActiveModel::Attributes

  attribute :start, :time
end

String values are parsed using the ISO 8601 datetime format, but are normalized to have a date of 2000-01-01 and be in the UTC time zone.

event = Event.new
event.start = "2004-10-25T01:23:45-06:00"

event.start.class # => Time
event.start       # => 2000-01-01 07:23:45 UTC

Partial time-only formats are also accepted.

event.start = "00:01:02+03:00"
event.start # => 1999-12-31 21:01:02 UTC

The degree of sub-second precision can be customized when declaring an attribute:

class Event
  include ActiveModel::Attributes

  attribute :start, :time, precision: 4
end

Instance Attribute Summary

Attributes inherited from Value

#limit, #precision, #scale

Instance Method Summary collapse

Methods included from Helpers::TimeValue

#apply_seconds_precision, #serialize_cast_value, #type_cast_for_schema

Methods included from Helpers::Timezone

#default_timezone, #is_utc?

Methods inherited from Value

#==, #as_json, #assert_valid_value, #binary?, #cast, #changed?, #changed_in_place?, #deserialize, #force_equality?, #hash, #initialize, #map, #mutable?, #serializable?, #serialize, #serialized?, #type_cast_for_schema, #value_constructed_by_mass_assignment?

Methods included from SerializeCastValue

included, #initialize, #itself_if_serialize_cast_value_compatible, serialize

Constructor Details

This class inherits a constructor from ActiveModel::Type::Value

Instance Method Details

#typeObject



45
46
47
# File 'lib/active_model/type/time.rb', line 45

def type
  :time
end

#user_input_in_time_zone(value) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/active_model/type/time.rb', line 49

def user_input_in_time_zone(value)
  return unless value.present?

  case value
  when ::String
    value = "2000-01-01 #{value}"
    time_hash = begin
      ::Date._parse(value)
    rescue ArgumentError
    end

    return if time_hash.nil? || time_hash[:hour].nil?
  when ::Time
    value = value.change(year: 2000, day: 1, month: 1)
  end

  super(value)
end