Method: Hanami::Utils::Kernel.Date

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

.Date(arg) ⇒ Date

Coerces the argument to be a Date.

Examples:

Basic Usage

require 'hanami/utils/kernel'

Hanami::Utils::Kernel.Date(Date.today)
  # => #<Date: 2014-04-17 ((2456765j,0s,0n),+0s,2299161j)>

Hanami::Utils::Kernel.Date(DateTime.now)
  # => #<Date: 2014-04-17 ((2456765j,0s,0n),+0s,2299161j)>

Hanami::Utils::Kernel.Date(Time.now)
  # => #<Date: 2014-04-17 ((2456765j,0s,0n),+0s,2299161j)>

Hanami::Utils::Kernel.Date('2014-04-17')
  # => #<Date: 2014-04-17 ((2456765j,0s,0n),+0s,2299161j)>

Hanami::Utils::Kernel.Date('2014-04-17 22:37:15')
  # => #<Date: 2014-04-17 ((2456765j,0s,0n),+0s,2299161j)>

Date Interface

require 'hanami/utils/kernel'

class Christmas
  def to_date
    Date.parse('Dec, 25')
  end
end

Hanami::Utils::Kernel.Date(Christmas.new)
  # => #<Date: 2014-12-25 ((2457017j,0s,0n),+0s,2299161j)>

Unchecked Exceptions

require 'hanami/utils/kernel'

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

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

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

Parameters:

  • arg (Object)

    the argument

Returns:

  • (Date)

    the result of the coercion

Raises:

  • (TypeError)

    if the argument can’t be coerced

Since:

  • 0.1.1

[View source]

716
717
718
719
720
721
722
723
724
# File 'lib/hanami/utils/kernel.rb', line 716

def self.Date(arg)
  if arg.respond_to?(:to_date)
    arg.to_date
  else
    Date.parse(arg.to_s)
  end
rescue ArgumentError, NoMethodError
  raise TypeError.new "can't convert #{inspect_type_error(arg)}into Date"
end