Class: StrongCSV::Types::Time

Inherits:
Base
  • Object
show all
Defined in:
lib/strong_csv/types/time.rb

Overview

Time type

Instance Method Summary collapse

Constructor Details

#initialize(format: "%Y-%m-%d") ⇒ Time

Returns a new instance of Time.

Parameters:

  • format (String) (defaults to: "%Y-%m-%d")

    The format of #strptime

Raises:

  • (ArgumentError)


8
9
10
11
12
13
# File 'lib/strong_csv/types/time.rb', line 8

def initialize(format: "%Y-%m-%d")
  raise ArgumentError, "`format` must be a String" unless format.is_a?(::String)

  super()
  @format = format
end

Instance Method Details

#cast(value) ⇒ ValueResult

Parameters:

  • value (Object)

    Value to be casted to Time

Returns:



17
18
19
20
21
22
23
# File 'lib/strong_csv/types/time.rb', line 17

def cast(value)
  return ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` can't be casted to Time with the format `#{@format.inspect}`"]) if value.nil?

  ValueResult.new(value: ::Time.strptime(value.to_s, @format), original_value: value)
rescue ArgumentError
  ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` can't be casted to Time with the format `#{@format.inspect}`"])
end