Class: ActiveModel::Type::Time

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

Overview

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

class Event
  include ActiveModel::Attributes

  attribute :start, :time
end

event = Event.new
event.start = "2022-02-18T13:15:00-05:00"

event.start.class # => Time
event.start.year  # => 2022
event.start.month # => 2
event.start.day   # => 18
event.start.hour  # => 13
event.start.min   # => 15
event.start.sec   # => 0
event.start.zone  # => "EST"

String values are parsed using the ISO 8601 datetime format. Partial time-only formats are also accepted.

event.start = "06:07:08+09:00"
event.start.utc # => 1999-12-31 21:07:08 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

Direct Known Subclasses

ActiveRecord::Type::Time

Instance Attribute Summary

Attributes inherited from Value

#limit, #precision, #scale

Instance Method Summary collapse

Methods included from Helpers::TimeValue

#apply_seconds_precision, #serialize, #type_cast_for_schema

Methods included from Helpers::Timezone

#default_timezone, #is_utc?

Methods inherited from Value

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

Constructor Details

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

Instance Method Details

#typeObject


47
48
49
# File 'activemodel/lib/active_model/type/time.rb', line 47

def type
  :time
end

#user_input_in_time_zone(value) ⇒ Object


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

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