Method: Hanami::Utils::Kernel.Time

Defined in:
lib/hanami/utils/kernel.rb

.Time(arg) ⇒ Time

Coerces the argument to be a Time.

Examples:

Basic Usage

require 'hanami/utils/kernel'

Hanami::Utils::Kernel.Time(Time.now)
  # => 2014-04-18 15:56:39 +0200

Hanami::Utils::Kernel.Time(DateTime.now)
  # => 2014-04-18 15:56:39 +0200

Hanami::Utils::Kernel.Time(Date.today)
  # => 2014-04-18 00:00:00 +0200

Hanami::Utils::Kernel.Time('2014-04-18')
  # => 2014-04-18 00:00:00 +0200

Hanami::Utils::Kernel.Time('2014-04-18 15:58:02')
  # => 2014-04-18 15:58:02 +0200

Time Interface

require 'hanami/utils/kernel'

class Epoch
  def to_time
    Time.at(0)
  end
end

Hanami::Utils::Kernel.Time(Epoch.new)
  # => 1970-01-01 01:00:00 +0100

Unchecked Exceptions

require 'hanami/utils/kernel'

# When nil
input = nil
Hanami::Utils::Kernel.Time(input) # => TypeError

# Missing #respond_to?
input = BasicObject.new
Hanami::Utils::Kernel.Time(input) # => TypeError

# Missing #to_s?
input = BasicObject.new
Hanami::Utils::Kernel.Time(input) # => TypeError

Parameters:

  • arg (Object)

    the argument

Returns:

  • (Time)

    the result of the coercion

Raises:

  • (TypeError)

    if the argument can’t be coerced

Since:

  • 0.1.1

[View source]

849
850
851
852
853
854
855
856
857
858
# File 'lib/hanami/utils/kernel.rb', line 849

def self.Time(arg)
  case arg
  when ->(a) { a.respond_to?(:to_time) } then arg.to_time
  when Numeric then Time.at(arg)
  else
    Time.parse(arg.to_s)
  end
rescue ArgumentError, NoMethodError
  raise TypeError.new "can't convert #{inspect_type_error(arg)}into Time"
end