Class: TTY::Conversion::BooleanConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/tty/conversion/converter/boolean.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source = String) ⇒ BooleanConverter

Returns a new instance of BooleanConverter.



11
12
13
14
# File 'lib/tty/conversion/converter/boolean.rb', line 11

def initialize(source = String)
  @source = source
  @target = [TrueClass, FalseClass]
end

Instance Attribute Details

#sourceObject (readonly)

Returns the value of attribute source.



9
10
11
# File 'lib/tty/conversion/converter/boolean.rb', line 9

def source
  @source
end

#targetObject (readonly)

Returns the value of attribute target.



7
8
9
# File 'lib/tty/conversion/converter/boolean.rb', line 7

def target
  @target
end

Instance Method Details

#boolean?(value) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/tty/conversion/converter/boolean.rb', line 16

def boolean?(value)
  target.any? { |klass| value.is_a?(klass) }
end

#convert(value) ⇒ Object

Convert value to boolean type including range of strings such as

other values coerced to false are:
  0, f, F, FALSE, false, False, n, N, No,  no,  No

Examples:

coerce("True") # => true

other values coerced to true are:
  1, t, T, TRUE,  true,  True,  y, Y, YES, yes, Yes
coerce("False") # => false

Parameters:

  • value (Object)


37
38
39
40
41
42
43
44
45
46
# File 'lib/tty/conversion/converter/boolean.rb', line 37

def convert(value)
  case value.to_s
  when /^(yes|y|t(rue)?|1)$/i
    return true
  when /^(no|n|f(alse)?|0)$/i
    return false
  else
    fail TypeError, "Expected boolean type, got #{value}"
  end
end