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.

type - Specify either :date, or :datetime type (default: date) 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_args, #source_metadata, #target_metadata

Instance Method Summary collapse

Methods inherited from Remi::Transform

#call, #to_proc

Constructor Details

#initialize(*args, type: nil, in_format: nil, out_format: nil, **kargs, &block) ⇒ FormatDate

Returns a new instance of FormatDate.



319
320
321
322
323
324
# File 'lib/remi/transform.rb', line 319

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

Instance Method Details

#class_typeObject



346
347
348
# File 'lib/remi/transform.rb', line 346

def class_type
  @class_type ||= type == :datetime ? Time : Date
end

#default_date_formatObject



338
339
340
341
342
343
344
# File 'lib/remi/transform.rb', line 338

def default_date_format
  if type == :datetime
    '%Y-%m-%d %H:%M:%S'
  else
    '%Y-%m-%d'
  end
end

#in_formatObject



330
331
332
# File 'lib/remi/transform.rb', line 330

def in_format
  @in_format ||= @source_metadata.fetch(:in_format, default_date_format)
end

#out_formatObject



334
335
336
# File 'lib/remi/transform.rb', line 334

def out_format
  @out_format ||= @source_metadata.fetch(:out_format, default_date_format)
end

#transform(value) ⇒ Object



350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/remi/transform.rb', line 350

def transform(value)
  begin
    if value.blank? then
      ''
    elsif value.respond_to? :strftime
      value.strftime(out_format)
    else
      class_type.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

#typeObject



326
327
328
# File 'lib/remi/transform.rb', line 326

def type
  @type ||= @source_metadata.fetch(:type, :date)
end