Method: Hanami::Utils::Kernel.Symbol

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

.Symbol(arg) ⇒ Symbol

Coerces the argument to be a Symbol.

Examples:

Basic Usage

require 'hanami/utils/kernel'

Hanami::Utils::Kernel.Symbol(:hello)  # => :hello
Hanami::Utils::Kernel.Symbol('hello') # => :hello

Symbol Interface

require 'hanami/utils/kernel'

class StatusSymbol
  def to_sym
    :success
  end
end

Hanami::Utils::Kernel.Symbol(StatusSymbol.new) # => :success

Unchecked Exceptions

require 'hanami/utils/kernel'

# When nil
input = nil
Hanami::Utils::Kernel.Symbol(input) # => TypeError

# When empty string
input = ''
Hanami::Utils::Kernel.Symbol(input) # => TypeError

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

Parameters:

  • arg (#to_sym)

    the argument

Returns:

  • (Symbol)

    the result of the coercion

Raises:

  • (TypeError)

    if the argument can’t be coerced

Since:

  • 0.2.0

[View source]

1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
# File 'lib/hanami/utils/kernel.rb', line 1015

def self.Symbol(arg)
  case arg
  when "" then raise TypeError.new "can't convert #{inspect_type_error(arg)}into Symbol"
  when ->(a) { a.respond_to?(:to_sym) } then arg.to_sym
  else # rubocop:disable Lint/DuplicateBranch
    raise TypeError.new "can't convert #{inspect_type_error(arg)}into Symbol"
  end
rescue NoMethodError
  raise TypeError.new "can't convert #{inspect_type_error(arg)}into Symbol"
end