Class: Remi::Transform::ParseDate

Inherits:
Remi::Transform show all
Defined in:
lib/remi/transform.rb

Overview

Public: Parses a string and converts it to a date. This transform is metadata aware and will use :in_format metadata from the source

in_format - The date format to use to convert the string (default: uses :in_format

from the source metadata.  If that is not defined, use '%Y-%m-%d').

if_blank - Value to use if the the incoming value is blank (default: uses :if_blank

from the source metadata.  If that is not defined, use nil).  If set to
:high, then use the largest date, if set to :ow, use the lowest date.

Examples:

ParseDate.new(in_format: '%m/%d/%Y').to_proc.call('02/22/2013') # => Date.new(2013,2,22)

tform = ParseDate.new
tform. = { in_format: '%m/%d/%Y' }
tform.to_proc.call('02/22/2013') # => Date.new(2013,2,22)

Instance Attribute Summary

Attributes inherited from Remi::Transform

#multi_arg, #source_metadata, #target_metadata

Instance Method Summary collapse

Methods inherited from Remi::Transform

#call, #to_proc

Constructor Details

#initialize(*args, in_format: nil, if_blank: nil, **kargs, &block) ⇒ ParseDate

Returns a new instance of ParseDate.



233
234
235
236
237
# File 'lib/remi/transform.rb', line 233

def initialize(*args, in_format: nil, if_blank: nil, **kargs, &block)
  super
  @in_format = in_format
  @if_blank  = if_blank
end

Instance Method Details

#blank_handler(value) ⇒ Object



265
266
267
268
269
270
271
272
273
274
275
# File 'lib/remi/transform.rb', line 265

def blank_handler(value)
  if if_blank == :low
    Date.new(1900,01,01)
  elsif if_blank == :high
    Date.new(2999,12,31)
  elsif if_blank.respond_to? :call
    if_blank.call(value)
  else
    if_blank
  end
end

#if_blankObject



243
244
245
# File 'lib/remi/transform.rb', line 243

def if_blank
  @if_blank ||= @source_metadata.fetch(:if_blank, nil)
end

#in_formatObject



239
240
241
# File 'lib/remi/transform.rb', line 239

def in_format
  @in_format ||= @source_metadata.fetch(:in_format, '%Y-%m-%d')
end

#string_to_date(value) ⇒ Object



261
262
263
# File 'lib/remi/transform.rb', line 261

def string_to_date(value)
  Date.strptime(value, in_format)
end

#transform(value) ⇒ Object



247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/remi/transform.rb', line 247

def transform(value)
  begin
    if value.respond_to?(:strftime)
      value
    elsif value.blank? then
      blank_handler(value)
    else
      string_to_date(value)
    end
  rescue ArgumentError => err
    raise err, "Error parsing date (#{value.class}): '#{value}' with format #{in_format})"
  end
end