Method: Hanami::Utils::Kernel.Boolean

Defined in:
lib/hanami/utils/kernel.rb

.Boolean(arg) ⇒ true, false

Coerces the argument to be a Boolean.

Examples:

Basic Usage

require 'hanami/utils/kernel'

Hanami::Utils::Kernel.Boolean(nil)                      # => false
Hanami::Utils::Kernel.Boolean(0)                        # => false
Hanami::Utils::Kernel.Boolean(1)                        # => true
Hanami::Utils::Kernel.Boolean('0')                      # => false
Hanami::Utils::Kernel.Boolean('1')                      # => true
Hanami::Utils::Kernel.Boolean(Object.new)               # => true

Boolean Interface

require 'hanami/utils/kernel'

Answer = Struct.new(:answer) do
  def to_bool
    case answer
    when 'yes' then true
    else false
    end
  end
end

answer = Answer.new('yes')
Hanami::Utils::Kernel.Boolean(answer) # => true

Unchecked Exceptions

require 'hanami/utils/kernel'

# Missing #respond_to?
input = BasicObject.new
Hanami::Utils::Kernel.Boolean(input) # => TypeError

Parameters:

  • arg (Object)

    the argument

Returns:

  • (true, false)

    the result of the coercion

Raises:

  • (TypeError)

    if the argument can’t be coerced

Since:

  • 0.1.1


901
902
903
904
905
906
907
908
909
910
911
912
913
914
# File 'lib/hanami/utils/kernel.rb', line 901

def self.Boolean(arg)
  case arg
  when Numeric
    arg.to_i == BOOLEAN_TRUE_INTEGER
  when ::String, Utils::String, BOOLEAN_FALSE_STRING
    Boolean(arg.to_i)
  when ->(a) { a.respond_to?(:to_bool) }
    arg.to_bool
  else
    !!arg
  end
rescue NoMethodError
  raise TypeError.new "can't convert #{inspect_type_error(arg)}into Boolean"
end