Class: Remi::Transform::FormatDate

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

Overview

Public: (Re)formats a date. This transform is metadata aware and will use :in_format/:out_format metadata from the source.

in_format - The date format to used to parse the input value. If the input value

is a date, then then parameter is ignored.  (default: uses :in_format
from the source metadata.  If that is not defined, use '%Y-%m-%d')

out_format - The date format applied to provide the resulting string. (default:

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

Examples:

FormatDate.new(in_format: '%m/%d/%Y', out_format: '%Y-%m-%d').to_proc.call('02/22/2013') # => "2013-02-22"

tform = FormatDate.new
tform. = { in_format: '%m/%d/%Y', out_format: '%Y-%m-%d' }
tform.to_proc.call('02/22/2013') # => "2013-02-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, out_format: nil, **kargs, &block) ⇒ FormatDate

Returns a new instance of FormatDate.



298
299
300
301
302
# File 'lib/remi/transform.rb', line 298

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

Instance Method Details

#in_formatObject



304
305
306
# File 'lib/remi/transform.rb', line 304

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

#out_formatObject



308
309
310
# File 'lib/remi/transform.rb', line 308

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

#transform(value) ⇒ Object



312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/remi/transform.rb', line 312

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