Class: Remi::Transform::EnforceType
Overview
Public: Enforces the type declared in the :type metadata field (if it exists)
Examples:
tform = EnforceType.new
tform.source_metadata = { type: :date, in_format: '%m/%d/%Y' }
tform.to_proc.call('02/22/2013')
tform = EnforceType.new
tform.source_metadata = { type: :integer }
tform.to_proc.call('12')
tform = EnforceType.new
tform.source_metadata = { type: :integer }
tform.to_proc.call('12A')
Instance Attribute Summary
#multi_args, #source_metadata, #target_metadata
Instance Method Summary
collapse
#call, #to_proc
Constructor Details
#initialize(*args, **kargs, &block) ⇒ EnforceType
Returns a new instance of EnforceType.
481
482
483
|
# File 'lib/remi/transform.rb', line 481
def initialize(*args, **kargs, &block)
super
end
|
Instance Method Details
#blank_handler(value) ⇒ Object
503
504
505
506
507
508
509
510
511
|
# File 'lib/remi/transform.rb', line 503
def blank_handler(value)
return value unless value.blank?
if if_blank.respond_to? :to_proc
if_blank.to_proc.call(value)
else
if_blank
end
end
|
#default_if_blank ⇒ Object
513
514
515
|
# File 'lib/remi/transform.rb', line 513
def default_if_blank
type == :string ? '' : nil
end
|
#if_blank ⇒ Object
497
498
499
500
501
|
# File 'lib/remi/transform.rb', line 497
def if_blank
return @if_blank if @if_blank_set
@if_blank_set = true
@if_blank = @source_metadata.fetch(:if_blank, default_if_blank)
end
|
489
490
491
|
# File 'lib/remi/transform.rb', line 489
def in_format
@in_format ||= @source_metadata.fetch(:in_format, '')
end
|
#scale ⇒ Object
493
494
495
|
# File 'lib/remi/transform.rb', line 493
def scale
@scale ||= @source_metadata.fetch(:scale, 0)
end
|
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
|
# File 'lib/remi/transform.rb', line 517
def transform(value)
if value.blank? && type != :json
blank_handler(value)
else
case type
when :string
value
when :integer
Integer(value)
when :float
Float(value)
when :decimal
Float("%.#{scale}f" % Float(value))
when :date
value.is_a?(Date) ? value : Date.strptime(value, in_format)
when :datetime
value.is_a?(Time) ? value : Time.strptime(value, in_format)
when :json
if value.blank? && value != [] && value != {}
blank_handler(value)
else
value.is_a?(Hash) || value.is_a?(Array) ? value : JSON.parse(value)
end
else
raise ArgumentError, "Unknown type enforcement: #{type}"
end
end
end
|
#type ⇒ Object
485
486
487
|
# File 'lib/remi/transform.rb', line 485
def type
@type ||= @source_metadata.fetch(:type, :string)
end
|