Class: CSVConverter::Converters::DateConverter

Inherits:
BaseConverter show all
Defined in:
lib/csv_converter/converters/date_converter.rb

Overview

Converts a string into a date

Instance Attribute Summary

Attributes inherited from BaseConverter

#options, #raw_data

Instance Method Summary collapse

Methods inherited from BaseConverter

#data, #empty_value?

Constructor Details

#initialize(raw_data, options = { date_format: '%m/%d/%y' }) ⇒ DateConverter

A new instance of DateConverter.

Parameters:

  • raw_data (String)

    the raw data of the attribute being processed.

  • options (Hash) (defaults to: { date_format: '%m/%d/%y' })

    the options for the converter provided in the mappings. Additionally, contains the details of the data being processed. See BaseConverter#option. The date_format key is required. If date_format is blank then an error is raised.



12
13
14
15
16
# File 'lib/csv_converter/converters/date_converter.rb', line 12

def initialize(raw_data, options = { date_format: '%m/%d/%y' })
  super(raw_data, options)

  validate_options
end

Instance Method Details

#callDate

Converts data into a Date using the format provided in the mappings.

Returns:

  • (Date)

    if an error occurs during conversion ‘nil` is returned.



20
21
22
23
24
# File 'lib/csv_converter/converters/date_converter.rb', line 20

def call
  call!
rescue CSVConverter::Error
  nullable_object
end

#call!Date

Converts data into a Date using the format provided in the mappings.

Returns:

  • (Date)

    if an error occurs during conversion an error is raised.



28
29
30
31
32
# File 'lib/csv_converter/converters/date_converter.rb', line 28

def call!
  Date.strptime(data, options[:date_format])
rescue StandardError => e
  raise CSVConverter::Error.new(e.message, options)
end