Class: Remi::Transform::Truthy

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

Overview

Public: Converts strings into booleans. Uses a regex to convert strings representing booleans to actual booleans. The truthy regex is /^(t|true|y|yes|1)$/i and the falsey regex is /^(f|false|n|no|0)$/i

allow_nils - Specifies whether to allow the result to include nils. If this is set

to false, then the value is only checked against the truthy regex and
the returned value is false if it doesn't match.  If allow_nils
is set to true, the both the truthy and the falsey regex are checked.
If neither match, then the result is nil.  (Default: false).

Examples:

Truthy.new.to_proc.call(‘True’) # => true Truthy.new.to_proc.call(‘Yes’) # => true Truthy.new.to_proc.call(‘y’) # => true Truthy.new.to_proc.call(‘Yessire’) # => false Truthy.new.to_proc.call(‘0’) # => false Truthy.new.to_proc.call(‘Pineapple’) # => false Truthy.new(allow_nils: false).to_proc.call(‘Pineapple’) # => nil

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, allow_nils: false, **kargs, &block) ⇒ Truthy

Returns a new instance of Truthy.



520
521
522
523
524
525
526
# File 'lib/remi/transform.rb', line 520

def initialize(*args, allow_nils: false, **kargs, &block)
  super
  @allow_nils = allow_nils

  @true_regex = /^(t|true|y|yes|1)$/i
  @false_regex = /^(f|false|n|no|0)$/i
end

Instance Method Details

#match_false(value) ⇒ Object



532
533
534
# File 'lib/remi/transform.rb', line 532

def match_false(value)
  !!value.match(@false_regex)
end

#match_true(value) ⇒ Object



528
529
530
# File 'lib/remi/transform.rb', line 528

def match_true(value)
  !!value.match(@true_regex)
end

#transform(value) ⇒ Object



536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
# File 'lib/remi/transform.rb', line 536

def transform(value)
  value = value.to_s

  if @allow_nils
    if match_true(value)
      true
    elsif match_false(value)
      false
    else
      nil
    end
  else
    match_true(value)
  end
end